revision:
An array is a special variable, which can hold more than one value at a time: it can hold many values under a single name, and the values can be access by referring to an index number.
Syntax: var array_name = [item1, item2, ...]; with JavaScript, the full array can be accessed by referring to the array name.
P.S. Note/Important: array indexes start with 0. [0] is the first element. [1] is the second element. JavaScript array elements are accessed using numeric indexes (starting from 0).
<div> <a id="ex1"></a><br> <a id="ex2"></a><br> <a id="ex3"></a><br> <a id="ex4"></a><br> <a id="ex5"></a><br> <a id="ex6"></a><br> <a id="ex7"></a><br> </div> <script> var fruit = ["Banana ", "Apple ", "Pear ", " Plum", " Mango", " Orange"]; document.getElementById('ex1').innerHTML = "fruits: " + fruit; document.getElementById('ex2').innerHTML = "fruit 0: " + fruit[0]; document.getElementById('ex3').innerHTML = "fruit 1: " + fruit[1]; document.getElementById('ex4').innerHTML = "fruit 2: " + fruit[2]; document.getElementById('ex5').innerHTML = "fruit 3: " + fruit[3]; document.getElementById('ex6').innerHTML = "fruits array length: " + fruit.length; document.getElementById('ex7').innerHTML = "fruits array: " + fruit; </script>
<div> <a id="ex8"></a><br> <a id="ex9"></a> </div> <script> let ninjas = ['shaun', 'ryu', 'chun-li']; ninjas[1] = 'ken'; document.getElementById('ex8').innerHTML = "ninjas: " + ninjas; document.getElementById('ex9').innerHTML = "ninja 1 in the array: " + ninjas[1]; </script>
<div> <a id="ex10"></a><br> <a id="ex11"></a><br> <a id="ex12"></a> </div> <script> // mix of values let arr = [ 'Apple', { name: 'John' }, true, {greeting: 'hello'} ]; document.getElementById('ex10').innerHTML = "object at index 1: " + (arr[1].name); // John document.getElementById('ex11').innerHTML = "object at index 3: " + arr[3].greeting; // hello document.getElementById('ex12').innerHTML = "object at index 2: " + arr[2]; </script>
<div> <a id="ex13"></a><br> <a id="ex14"></a><br> <a id="ex15"></a><br> </div> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; var first = fruits[0]; var last = fruits[fruits.length-1]; var third = fruits[2]; document.getElementById("ex13").innerHTML = "using the first index [0]: " + first; document.getElementById("ex14").innerHTML = "using the last index [4-1]: " + last; document.getElementById("ex15").innerHTML = "using the third index [2]: " + third; </script>
<div> <a id="ex16"></a><br> <a id="ex17"></a><br> <a id="ex18"></a><br> <a id="ex19"></a><br> <a id="ex20"></a> </div> <script> let listOfNumbers = [2, 3, 5, 7, 11]; document.getElementById('ex16').innerHTML = "array: " + listOfNumbers; document.getElementById('ex17').innerHTML = "index 2 in array: " + listOfNumbers[2]; document.getElementById('ex18').innerHTML = "index 4 in array: " + listOfNumbers[4]; document.getElementById('ex19').innerHTML = "index 0 in array: " + listOfNumbers[0]; document.getElementById('ex20').innerHTML = "slicing 2 - 1 in array: " + listOfNumbers[2 - 1]; </script>
Spaces and line breaks are not important. A declaration can span multiple lines.
Examples
<div> <a id="ex21"></a><br> <a id="ex22"></a><br> <a id="ex23"></a><br> <a id="ex24"></a><br> </div> <script> var fruit_1, text, fLen, i; fruit_1 = ["Banana", "Orange", "Apple", "Mango"]; fLen = fruit_1.length; text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>"; document.getElementById("ex21").innerHTML = "for loop: " + text; let random = ['shaun' , 'crystal', 30, 40]; document.getElementById('ex23').innerHTML = "array: " + random; document.getElementById('ex24').innerHTML = "array length: " + random.length; </script>
Syntax: array.at(index)
parameters:
index (optional). The index (position) of the array element to be returned. Default is 0. -1 returns the last element.
The at() method returns the same as [].
Example
<div> <p id="ex25"></p> <p id="ex26"></p> <p id="ex27"></p> <p id="ex28"></p> </div> <script> const vruchten = ["Banana", "Orange", "Apple", "Mango"]; let vrucht = vruchten.at(); let vrucht_1 = vruchten.at(2); let vrucht_2 = vruchten.at(-1); document.getElementById("ex25").innerHTML = "fruit: " + vruchten; document.getElementById("ex26").innerHTML = vrucht; document.getElementById("ex27").innerHTML = vrucht_1; document.getElementById("ex28").innerHTML = vrucht_2; </script>
Syntax : array1.concat(array2, array3, ..., arrayX)
The concat() method returns a new array, containing the joined arrays. It does not change the existing arrays.
parameters:
array1,... : required. The array(s) to be concatenated.
Example
<div> <a id="ex29"></a> <p id="ex30"></p> <p id="ex31"></p> <p id="ex32"></p> <p id="ex33"></p> <p id="ex34"></p> </div> <script> let result2 = ninjas.concat(['ken', 'crystal']); document.getElementById('ex29').innerHTML = "ninjas.concat: " + result2; const arr_1a = ["Cecilie", "Lone"]; const arr_2a = [1, 2, 3]; const arr_3a = arr_1a.concat(arr_2a); document.getElementById("ex30").innerHTML = "arrays concat: " + arr_3a; let arr7 = [1, 2]; document.getElementById('ex31').innerHTML = "original array: " + arr7; document.getElementById('ex32').innerHTML = "concatenate 1: " + arr7.concat([3, 4]); document.getElementById('ex33').innerHTML = "concatenate 2: " + arr7.concat([3, 4], [5, 6]); document.getElementById('ex34').innerHTML = "concatenate 3: " + arr7.concat([3, 4], 5, 6); </script>
Syntax: array.constructor
For JavaScript arrays the constructor property returns: function Array() { [native code] }
Example
<div> <p id="ex35"></p> <p id="ex36"></p> </div> <script> const vruchten_1 = ["Banana", "Orange", "Apple", "Mango"]; let text_1 = vruchten_1.constructor; document.getElementById("ex35").innerHTML = "fruits: " + vruchten_1; document.getElementById("ex36").innerHTML = text_1; </script>
Syntax: array.copyWithin(target, start, end)
parameters:
target : required. The index (position) to copy the elements to.
start : optional. The start index (position). Default is 0.
end : optional. The end index (position). Default is the array length.
The copyWithin() method overwrites the existing values and does not add items to the array.
Example
<div> <p id="ex37"></p> <p id="ex38"></p> <p id="ex39"></p> </div> <script> const vruchten_2 = ["Banana", " Orange", " Apple", " Mango", " Kiwi", " Papaya"]; document.getElementById("ex37").innerHTML = "array is: " + vruchten_2; document.getElementById("ex38").innerHTML = " after copyWithin: " + vruchten_2.copyWithin(2,0); document.getElementById("ex39").innerHTML = " after copyWithin: " + vruchten_2.copyWithin(2,0, 2); </script>
Syntax: array.entries()
parameters: none
The entries() method does not change the original array.
Example
<div> <p id="ex40"></p> <p id="ex1a"></p> </div> <script> const vruchten_3 = ["Banana", "Orange", "Apple", "Mango"]; const f = vruchten_3.entries(); document.getElementById("ex40").innerHTML = "fruits: " + vruchten_3; for (let x of f) { document.getElementById("ex1a").innerHTML += x + "<br>"; } </script>
Syntax: array.every(function(currentValue, index, arr), thisValue)
parameters:
function : required. A function to be run for each element in the array.
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default "undefined". A value passed to the function as its this value.
The every() method executes a function for each array element. It returns true if the function returns true for all elements. It returns false if the function returns false for one element. The every() method does not execute the function for empty elements and does not change the original array.
Example
<div> <p id="ex2a"></p> <p id="ex3a"></p> </div> <script> const ages = [32, 33, 16, 40]; document.getElementById("ex2a").innerHTML = "ages: " + ages; document.getElementById("ex3a").innerHTML = ages.every(checkAge); function checkAge(age) { return age > 18; } </script>
Syntax:array.fill(value, start, end)
parameters:
value : required. The value to fill in.
start : optional. The start index (position). Default is 0.
end : optional. The stop index (position). Default is array length.
The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.
Example
<div> <p id="ex4a"></p> <p id="ex5a"></p> <p id="ex6a"></p> </div> <script> const vruchten_4 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex4a").innerHTML = "fruits: " + vruchten_4; document.getElementById("ex5a").innerHTML = vruchten_4.fill("Kiwi"); document.getElementById("ex6a").innerHTML = vruchten_4.fill("Pear",2,4); </script>
Syntax: array.filter(function(currentValue, index, arr), thisValue)
parameters:
function : required. A function to run for each array element.
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default "undefined". A value passed to the function as its this value.
The filter() method creates a new array filled with elements that pass a test provided by a function. It does not execute the function for empty elements and does not change the original array.
Example
Click "test" to get every element in the array that has a value above this number:
<div> <p id="ex7a"></p> <p id="ex8a"></p><br> <p>Click "test" to get every element in the array that has a value above this number:</p> <p><input type="number" id="ageToCheck" value="30"></p> <button onclick="ageCheck()">test</button> <p id="ex9a"></p> </div> <script> const leeftijden = [32, 33, 16, 40]; document.getElementById("ex7a").innerHTML = "ages: " + leeftijden document.getElementById("ex8a").innerHTML = leeftijden.filter(checkAdult); function checkAdult(leeftijd) { return leeftijd >= 18; } const leeftijden_a = [32, 33, 12, 40, 16, 54]; function checkAge(leeftijd_a) { return leeftijd_a > document.getElementById("ageToCheck").value; } function ageCheck() { document.getElementById("ex9a").innerHTML = leeftijden_a.filter(checkAge); } </script>
Syntax: array.find(function(currentValue, index, arr),thisValue)
parameters:
function : required. A function to run for each array element.
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default "undefined". A value passed to the function as its this value.
The find() method executes a function for each array element and returns undefined if no elements are found. It does not execute the function for empty elements and does not change the original array.
Example
Click "test" to return the value of the first element in the array that has a value above this number:
<div> <p id="ex10a"></p> <p id="ex11a"></p><br> <p>Click "test" to return the value of the first element in the array that has a value above this number:</p> <p><input type="number" id="ageToCheck_c" value="18"></p> <button onclick="leeftijdFunctie()">test</button> <p id="ex12a"></p> </div> <script> const leeftijden_b = [3, 10, 18, 20, 24, 35]; document.getElementById("ex10a").innerHTML = "ages: " + leeftijden_b document.getElementById("ex11a").innerHTML = leeftijden_b.find(checkLeeftijd); function checkLeeftijd(leeftijd_b) { return leeftijd_b > 18; } const leeftijden_c = [4, 12, 16, 20, 30, 35, 53, 67, 72]; function leeftijdCheck(leeftijd_c) { return leeftijd_c > document.getElementById("ageToCheck_c").value; } function leeftijdFunctie() { document.getElementById("ex12a").innerHTML = leeftijden_c.find(leeftijdCheck); } </script>
Use the built-in find() method to find an element matching a specific criterion.
base
const fruits = [ { type: "Banana", color: "Yellow" }, { type: "Apple", color: "Green" } ]; const animals = [ {name: 'octopus', animalClass: 'invertebrates'}, {name: 'shark', animalClass: 'fish'}, {name: 'toad', animalClass: 'amphibians'}, {name: 'snake', animalClass: 'reptiles'}, {name: 'ostrich', animalClass: 'birds'}, {name: 'cat', animalClass: 'mammals'}, ]
longhand
let yellowFruit; for (let i = 0; i < fruits.length; ++i) { if (fruits[i].color === "Yellow") { yellowFruit = fruits[i]; } } function findReptile(name){ for(let i=0; i < animals.length; ++i){ if(animals[i].animalClass === 'reptiles' && animals[i].name === name){ return animals[i] } } }
shorthand
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow"); findReptile = name => ( animals.find(animal => animal.animalClass ==='reptiles' && animal.name === name) )
Instead of writing a "for loop" you can use the spread operator of array.reduce()./p>
base
var numbers = [25, 45, 15, -5, 73, 6]; const arr = [2, 8, 15, 4];
longhand
var maxValue = Math.max.apply(null, numbers); var minValue = Math.min.apply(null, numbers);
shorthand
var maxValue = Math.max(...numbers); // 73 var minValue = Math.min(...numbers); // -5 Math.max(...arr); // 15 Math.min(...arr); // 2
Syntax: array.findIndex(function(currentValue, index, arr), thisValue)
function : required. A function to run for each array element.
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default "undefined". A value passed to the function as its this value.
The findIndex() method executes a function for each array element and returns the index (position) of the first element that passes a test. It returns -1 if no match is found. It does not execute the function for empty elements and does not change the original array.
Example
Click "test" to return the index of the first array element that has a value above this number:
<div> <p id="ex13a"></p> <p id="ex14a"></p><br> <p>Click "test" to return the index of the first array element that has a value above this number:</p> <p><input type="number" id="toCheck" value="21"></p> <button onclick="numberFunction()">test</button> <p id="ex15a"></p> </div> <script> const ages_h = [3, 10, 18, 20]; document.getElementById("ex13a").innerHTML = "ages: " + ages_h; document.getElementById("ex14a").innerHTML = ages_h.findIndex(checkAge_h); function checkAge_h(age) { return age > 18; } const numbers_A = [4, 12, 16, 20, 25, 34, 67]; function checkValue1(x) { return x > document.getElementById("toCheck").value; } function numberFunction() { document.getElementById("ex15a").innerHTML = numbers_A.findIndex(checkValue1); } </script>
Syntax : array.flat(depth)
parameters:
depth : optional. How deep a nested array should be flattened. Default is 1.
Example
<div> <p id="ex16a"></p> <p id="ex17a"></p><br> <p id="ex18a"></p> <p id="ex19a"></p> </div> <script> const Array_a = [[1,2],[3,4],[5,6]]; const newArr = Array_a.flat(); document.getElementById("ex16a").innerHTML = "original array: " + JSON.stringify(Array_a); document.getElementById("ex17a").innerHTML = newArr; const Array_b = [1, 2, [3, [4, 5, 6], 7], 8]; document.getElementById("ex18a").innerHTML = "original array: " + JSON.stringify(Array_b); const newArr_b = Array_b.flat(2); document.getElementById("ex19a").innerHTML = newArr_b; </script>
Syntax: array.flatMap(function(currentValue, index, arr), thisValue)
parameters:
function : required. A function to be run for each array element..
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default value "undefined". A value passed to the function to be used as its "this" value.
"flatMap()" does not execute the function for empty elements and does not change the original array.
Example
<div> <p id="ex20a"></p> <p id="ex21a"></p> </div> <script> const Array_c = [1, 2, 3, 4, 5,6]; document.getElementById("ex20a").innerHTML = "original array: " + JSON.stringify(Array_c); const newArr_c = Array_c.flatMap((x) => x * 2); document.getElementById("ex21a").innerHTML = "new array: " + newArr_c; </script>
Syntax: array.forEach(function(currentValue, index, arr), thisValue)
parameters:
function : required. A function to be run for each array element..
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default value "undefined". A value passed to the function to be used as its "this" value.
The "forEach() method" does not execute the function for empty elements.
Example
<div> <p id="ex22a"></p> <p id="ex23a"></p> <p id="ex24a"></p><br> <p id="ex25a"></p> </div> <script> let som = 0; const nummers = [65, 44, 12, 4]; document.getElementById("ex22a").innerHTML = nummers; nummers.forEach(firstFunction); document.getElementById("ex23a").innerHTML = som; function firstFunction(item) { som += item; } nummers.forEach(secondFunction); document.getElementById("ex24a").innerHTML = nummers; function secondFunction(item_b, index, arr) { arr[index] = item_b * 10; } ["Bilbo", "Gandalf", "Nazgul", "Louis"].forEach((item, index, array) => { document.getElementById('ex25a').innerHTML += "index in array: " + (`${item} is at index ${index} in ${array}`) + "<br>"; }); </script>
Syntax: Array.from(object, mapFunction, thisValue)
parameters:
object :required. The object to convert to an array. .
mapFunction : optional. A map function to call on each item.
thisValue : optional. A value to use as "this" for the mapFunction.
The "Array.from() method" returns an array from any object with a length property. It returns an array from any iterable object.
Example
<div> <p id="ex26a"></p> <p id="ex27a"></p> </div> <script> let text_d = "ABCDEFG" document.getElementById("ex26a").innerHTML = "text: " + text_d const Array_d = Array.from(text_d); document.getElementById("ex27a").innerHTML = "array: " + Array_d; </script>
Syntax: array.includes(element, start)
parameters:
element : required. The value to search for.
start : optional. Start position. Default is 0.
The "includes() method" returns true if an array contains a specified value and false if the value is not found. The includes() method is case sensitive.
Example
<div> <p id="ex28a"></p> <p id="ex29a"></p> <p id="ex30a"></p> </div> <script> const fruits_p = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex28a").innerHTML = "fruits: " + fruits_p; document.getElementById("ex29a").innerHTML = "includes Mango: " + fruits_p.includes("Mango"); document.getElementById("ex30a").innerHTML = "includes Pear: " + fruits_p.includes("Pear"); </script>
Instead of using the indexOf() method to check if an element is in the array, you can use the includes() method, which determines whether an array includes a certain value among its entries, returning true or false as appropriate.
base
let numbers = [1, 2, 3]; var str = "Welcome to javascript tutorial"; let str = 'JavaScript String';
longhand
const hasNumber1 = numbers.indexOf(1) > -1 // -> True
shorthand
const hasNumber1 = numbers.includes(1) // -> True console.log(str.includes("javascript")); // -> True console.log(str.includes('Script', 5)); // -> False
Avoid condition chains using the includes() method.
base
const num = 1;
longhand
if(num == 1 || num == 2 || num == 3){ console.log("Yay"); if (value === 1 || value === 'one' || value === 2 || value === 'two') { //Execute code }
shorthand
if([1,2,3].includes(num)){ console.log("Yay"); } if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { //Execute code } if ([1, 'one', 2, 'two'].includes(value)) { //Execute code }
Syntax: array.indexOf(item, start)
parameters:
item : required. The value to search for.
start : optional. Where to start the search. Default value is 0. Negative values start the search from the end of the array.
The "indexOf() method" returns the first index (position) of a specified value. It returns -1 if the value is not found. The method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last. Negative start values counts from the last element (but still searches from left to right).
Example
<div> <a id="ex31a"></a><br> <a id="ex32a"></a><br><br> <a id="ex33a"></a><br> <a id="ex34a"></a><br><br> <a id="ex35a"></a><br> <a id="ex36a"></a><br> <a id="ex37a"></a><br> <a id="ex38a"></a><br> <a id="ex39a"></a><br><br> </div> <script> const fruits_q = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex31a").innerHTML = "array: " + fruits_q; let index_q = fruits_q.indexOf("Apple"); document.getElementById("ex32a").innerHTML = "index of Apple: " +index_q; const fruits_r = ["Banana", "Orange", "Apple", "Mango", "Apple"]; document.getElementById("ex33a").innerHTML = "array: " + fruits_r; let index_r = fruits_r.indexOf("Apple", 3); document.getElementById("ex34a").innerHTML = "index of Apple starting from index 3: " + index_r; let arr8 = [1, 0, false]; document.getElementById('ex35a').innerHTML = "orginal array: " + arr8; document.getElementById('ex36a').innerHTML = " index of zero: " + arr8.indexOf(0); document.getElementById('ex37a').innerHTML = " index of false: " + arr8.indexOf(false); document.getElementById('ex38a').innerHTML = " index of null: " + arr8.indexOf(null); document.getElementById('ex39a').innerHTML = "one is included: " +arr8.includes(1); </script>
bitwise indexOf:
When performing a lookup using an array, the indexOf() function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1 is returned. In JavaScript, 0 is considered 'falsy', while numbers greater or lesser than 0 are considered 'truthy'. The bitwise(~) operator will return a truthy value for anything but -1. Negating it is as simple as doing !~. Alternatively, we can also use the includes() function.
longhand
if(arr.indexOf(item) > -1) { // Confirm item IS found } if(arr.indexOf(item) === -1) { // Confirm item IS NOT found }
shorthand
if(~arr.indexOf(item)) { // Confirm item IS found } if(!~arr.indexOf(item)) { // Confirm item IS NOT found }
Syntax: Array.isArray(obj)
parameters:
obj : required. An object (or any data type) to be tested.
The "isArray()" method returns true if an object is an array, otherwise false.
Example
<div> <a id="ex40a"></a> <br><br> <a id="ex1b"></a> </div> <script> const fruits_s = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex40a").innerHTML = "array: " + fruits_s; let result_s = Array.isArray(fruits_s); document.getElementById("ex1b").innerHTML = "is array?: " + result_s; let text_t = "W3Schools"; let result_t = Array.isArray(text_t); document.getElementById("ex2b").innerHTML = "is array?: " + result_t; </script>
Syntax: array.join(separator)
parameters:
separator : optional. The separator to be used. Default is a comma.
The "join() method" does not change the original array. Any separator can be specified. The default is comma (,).
Example
<div> <p id="ex3b"></p> <p id="ex4b"></p> <p id="ex5b"></p> <p id="ex6b"></p> </div> <script> const fruits_u = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex3b").innerHTML = "fruits: " + JSON.stringify(fruits_u); let text_u = fruits_u.join(); document.getElementById("ex4b").innerHTML = "joined array: " + text_u; let text_v = fruits_u.join(" and "); document.getElementById("ex5b").innerHTML = "joined array using 'and: " + text_v; document.getElementById("ex6b").innerHTML = "joined array using '*': " + fruits_u.join(" * "); </script>
Syntax: array.keys()
parameters: none.
The "keys() method" does not change the original array.
Example
<div> <p id="ex7b"></p> <p id="ex8b"></p> <p id="ex9b"></p> </div> <script> const fruits_w = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex7b").innerHTML = "array: " + fruits_w; const keys = fruits_w.keys(); let text_w = ""; for (let x of keys) { text_w += x + " , "; } document.getElementById("ex8b").innerHTML = "keys: " + text_w; const keys_w = Object.keys(fruits_w); let text_ww = ""; for (let x of keys_w) { text_ww += x + " , "; } document.getElementById("ex9b").innerHTML = "keys: " + text_ww; </script>
Syntax: array.lastIndexOf(item, start)
parameters:
item : required. The value to search for .
start : optional. Where to start the search. Default is the last element (array.length-1). Negative start values counts from the last element (but still searches from right to left).
The "lastIndexOf() method" returns -1 if the value is not found. It starts at a specified index and searches from right to left. By defalt the search starts at the last element and ends at the first. Negative start values counts from the last element (but still searches from right to left).
Example
<div> <p>Click the button to locate the last occurrence of "planet".</p> <a id="ex10b"></a><br> <button onclick="myFunctionA()">try it</button><br><br> <a id="ex11b"></a><br> <p id="ex12b"></p> <p id="ex13b"></p> <p id="ex14b"></p> <p id="ex15b"></p> <p id="ex16b"></p> </div> <script> var str = "Hello planet earth, you are a great planet."; document.getElementById("ex10b").innerHTML = str; function myFunctionA() { var n = str.lastIndexOf("planet"); document.getElementById("ex11b").innerHTML = "lastIndexOf of 'planet': " + n; } const fruits_x = ["Orange", "Apple", "Orange", "Banana", "Apple", "Mango", "Banana"]; document.getElementById("ex12b").innerHTML = "array: " + fruits_x; let index_x = fruits_x.lastIndexOf("Apple"); document.getElementById("ex13b").innerHTML = "last index of Apple: " + index_x; let index_xx = fruits_x.lastIndexOf("Apple", 1); document.getElementById("ex14b").innerHTML = "last index of Apple, starting from index 1: " + index_xx; let index_xxx = fruits_x.lastIndexOf("Apple", 4); document.getElementById("ex15b").innerHTML = "last index of Apple, starting from index 4: " + index_xxx; let index_xxxx = fruits_x.lastIndexOf("Apple", -2); document.getElementById("ex16b").innerHTML = "last index of Apple, starting from index -1: " + index_xxxx; </script>
Syntax: return the length of an array: array.length; set the length of an array: array.length = number
parameters: none.
The "length" property provides an easy way to append new elements to an array without using the push() method.
Example
<div> <p id="ex17b"></p> <p id="ex18b"></p> <p id="ex19b"></p> <p id="ex20b"></p><br> <p id="ex21b"></p> <p id="ex22b"></p><br> <p>append new elements to the array</p> <a id="ex23b"></a><br> <button onclick="appendFunction()">try it</button><br><br> <a id="ex24b"></a> </div> <script> const fruits_y = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex17b").innerHTML = "array: " + fruits_y; let length = fruits_y.length; document.getElementById("ex18b").innerHTML = "array length: " + length; fruits_y.length = 2; document.getElementById("ex19b").innerHTML = "array length set to 2: " + fruits_y; document.getElementById("ex20b").innerHTML = "length of fruit array: " + length; let array_A = ["Bilbo", "Gandalf", "Nazgul"]; let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); document.getElementById("ex21b").innerHTML = "array: " + array_A; document.getElementById('ex22b').innerHTML = "length of items in array: " + lengths; const fruits6 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex23b").innerHTML = "original array: " + fruits6; function appendFunction() { fruits6[fruits6.length] = "Lemon"; document.getElementById("ex24b").innerHTML = "extended array: " + fruits6; } </script>
Syntax: array.map(function(currentValue, index, arr), thisValue)
parameters:
function : required. A function to be run for each array element..
currentValue : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array of the current element.
thisValue : optional. Default value "undefined". A value passed to the function to be used as its "this" value.
The "map() method" does not execute the function for empty elements and does not change the original array.
Example
<div> <p id="ex25b"></p> <p id="ex26b"></p> <p id="ex27b"></p><br> <p id="ex28b"></p> <p id="ex29b"></p> </div> <script> const numbers_a = [4, 9, 16, 25]; document.getElementById("ex25b").innerHTML = "numbers: " +numbers_a; document.getElementById("ex26b").innerHTML = "math-sqrt of numbers: " + numbers_a.map(Math.sqrt); const newArray_a = numbers_a.map(calcFunction); function calcFunction(num) { return num * 10; } document.getElementById("ex27b").innerHTML = "new array created with 'map': " + newArray_a; const persons = [ {firstname : "Malcom", lastname: "Reynolds"}, {firstname : "Kaylee", lastname: "Frye"}, {firstname : "Jayne", lastname: "Cobb"} ]; document.getElementById("ex28b").innerHTML = "array: " + "<br>" + JSON.stringify(persons); document.getElementById("ex29b").innerHTML = "get full name: " + persons.map(getFullName); function getFullName(item) { return [item.firstname,item.lastname].join(" "); } </script>
Syntax: array.pop()
The "pop() method" changes the original array. It returns the removed element.
parameters: none.
Example
<div> <a id="ex30b"></a><br> <a id="ex31b"></a><br><br> <a id="ex32b"></a><br> <a id="ex33b"></a><br> <a id="ex34b"></a><br><br> <a id="ex35b"></a><br> <a id="ex36b"></a><br> <a id="ex37b"></a><br> </div> <script> let ninjas_a = ['shaun', 'ryu', 'chun-li', 'darrel', 'revital']; document.getElementById('ex30b').innerHTML = "original array: " + ninjas_a; let result_a = ninjas_a.pop(); let result_b = ninjas_a.pop(); document.getElementById('ex31b').innerHTML = "ninjas_a.pop(): " + result_a; document.getElementById('ex32b').innerHTML = "ninjas_a.pop(): " + result_b; let fruits1 = ["Apple", "Orange", "Pear"]; document.getElementById('ex32b').innerHTML = "original array: " + fruits1; document.getElementById('ex33b').innerHTML = "fruits pop(): " + (fruits1.pop()); document.getElementById('ex34b').innerHTML = "new array: " + fruits1; let sequence = [1, 2, 3]; sequence.push(4); sequence.push(5); document.getElementById('ex35b').innerHTML = "sequence: " + sequence; document.getElementById('ex36b').innerHTML = "sequence.pop(): " + sequence.pop(); document.getElementById('ex37b').innerHTML = "sequence after pop(): " + sequence; </script>
Syntax: Array.prototype.name = value
parameters: none.
"prototype" is a property available with all JavaScript objects.
Warning!!! You are not advised to change the prototype of an object that you do not control. You should not change the prototype of built in JavaScript datatypes like: Numbers, Strings, Arrays, Dates, Booleans, Function, Objects. Only change the prototype of your own objects.
Example
<div> <p id="ex38b"></p> <p id="ex39b"></p><br> <p id="ex40b"></p> <p id="ex1c"></p> <p id="ex2c"></p> </div> <script> // Add a new method Array.prototype.myUcase = function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toUpperCase(); } }; // Use the method on any array const fruits_z = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex38b").innerHTML = "original array: " + fruits_z; fruits_z.myUcase(); document.getElementById("ex39b").innerHTML = "array with new method: " + fruits_z; function Person(first, last, eye) { this.firstName = first; this.lastName = last; this.eyeColor = eye; } const myFather = new Person("John", "Doe", "blue"); const myMother = new Person("Sally", "Rally", "green"); Person.prototype.nationality = "English"; document.getElementById("ex40b").innerHTML = JSON.stringify(myFather); document.getElementById("ex1c").innerHTML = JSON.stringify(myMother); document.getElementById("ex2c").innerHTML = "My father is " + myFather.nationality + "<br>" + "My mother is " + myMother.nationality; </script>
Syntax: array.push(item1, item2, ..., itemX)
parameters:
item1, item2, ..., itemX : The item(s) to add to the array. Minimum one item is required.
Example
<div> <a id="ex3c""></a><br> <a id="ex4c""></a><br><br> <a id="ex5c""></a><br> <a id="ex6c""></a><br> <a id="ex7c""></a><br> <a id="ex8c""></a><br> </div> <script> let ninjas_b = ['shaun', 'ryu', 'chun-li', 'darrel', 'revital', 'karel']; document.getElementById('ex3c').innerHTML = "original array: " + ninjas_b; let result_3 = ninjas_b.push('ken'); document.getElementById('ex4c').innerHTML = "ninjas.push(): " + result_3; const garden = ["Banana", " Orange", " Apple", " Mango"]; document.getElementById('ex5c').innerHTML = "original array: " + garden; garden.push(" Kiwi", " Lemon", " Pineapple"); document.getElementById("ex6c").innerHTML = "array after push(): " + garden; document.getElementById("ex7c").innerHTML = "adding element to array: " + garden.push(" Strawberry"); document.getElementById("ex8c").innerHTML = "array after new push(): " + garden; </script>
Syntax: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
parameters:
function : required. A function to be run for each element in the array..
total : required. The initialValue, or the previously returned value of the function.
currentValue : required. The value of the current element.
currentIndex : optional. The index of the current element.
arr : optional. The array the current element belongs to.
initialValue : optional. A value to be passed to the function as the initial value.
The "reduce() method" returns a single value: the function's accumulated result. It does not execute the function for empty array elements and does not change the original array.
At the first callback, there is no return value from the previous callback. Normally, array element 0 is used as initial value, and the iteration starts from array element 1.If an initial value is supplied, this is used, and the iteration starts from array element 0.
Example
<div> <a id="ex9c"></a><br> <a id="ex10c"></a><br><br> <a id="ex11c"></a><br> <a id="ex12c"></a><br> </div> <script> const numbers_d = [175, 50, 25]; document.getElementById('ex9c').innerHTML = "original array: " + numbers_d; document.getElementById("ex10c").innerHTML = "after reduce(): " + numbers_d.reduce(reduceFunc); function reduceFunc(total, num) { return total - num; } const numbers_e = [15.5, 2.3, 1.1, 4.7]; document.getElementById('ex11c').innerHTML = "original array: " + numbers_e; document.getElementById("ex12c").innerHTML = "after reduce(): " + numbers_e.reduce(getSum, 0); function getSum(total, num) { return total + Math.round(num); } </script>
Instead of writing a "for loop" you can use the spread operator of array.reduce()./p>
base
var numbers = [25, 45, 15, -5, 73, 6]; const arr = [2, 8, 15, 4];
longhand
var maxValue = Math.max.apply(null, numbers); var minValue = Math.min.apply(null, numbers);
shorthand
var maxValue = Math.max(...numbers); // 73 var minValue = Math.min(...numbers); // -5 Math.max(...arr); // 15 Math.min(...arr); // 2
Get average value of arguments: the reduce method can be used to get the average value of the arguments that are provided in this function.
Example - code
const average = (...args) => args.reduce((a, b) => a + b)/args.length; average(1, 2, 3, 4); // Result: 2.5
const average = arr => arr.reduce((a, b) => a + b)/arr.length; average([21, 56, 23, 122, 67]) //57.8
const average = arr => arr.reduce((a, b) => a + b, 0)/arr.length; average(1, 2, 3, 4); // Result: 2.5
Syntax: array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
parameters:
function : required. A function to be run for each element in the array..
total : required. The initialValue, or the previously returned value of the function.
currentValue : required. The value of the current element.
currentIndex : optional. The index of the current element.
arr : optional. The array the current element belongs to.
initialValue : optional. A value to be passed to the function as the initial value.
The "reduceRight() method" works from right to left and returns a single value: the function's accumulated result. It does not execute the function for empty array elements and does not change the original array.
At the first callback, there is no return value from the previous callback. Normally, the last array element is used as initial value, and the iteration starts from array the element before. If an initial value is supplied, this is used, and the iteration starts from the last element.
Example
<div> <a id="ex13c"></a><br> <a id="ex14c"></a><br><br> <a id="ex15c"></a><br> <a id="ex16c"></a><br> </div> <script> const numbers_f = [175, 50, 25]; document.getElementById("ex13c").innerHTML = "original array: " + numbers_f document.getElementById("ex14c").innerHTML = "after reduceRight(): " + numbers_f.reduceRight(reduceRightFunc); function reduceRightFunc(total, num) { return total - num; } const numbers_g = [2, 45, 30, 100]; document.getElementById("ex15c").innerHTML = "original array: " + numbers_g document.getElementById("ex16c").innerHTML = "after reduceRight(): " + numbers_g.reduceRight(getSum_a); function getSum_a(total, num) { return total - num; } </script>
Syntax: array.reverse()
parameters: none.
The "reverse() method" overwrites the original array.
Example
<div> <a id="ex17c"></a><br> <p>Click the button to reverse the order of the elements in the array.</p> <button onclick="myFunctionB()">Try it</button><br> <a id="ex18c"></a><br> </div> <script> var fruits2 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex17c").innerHTML = "fruits array: " + fruits2; function myFunctionB() { fruits2.reverse(); document.getElementById("ex18c").innerHTML = "fruits array reverse: " + fruits2; } </script>
Syntax: array.shift()
parameters: none.
The "shift() method" changes the original array.
Example
<div> <a id="ex19c"></a><br> <a id="ex20c"></a><br> <a id="ex21c"></a><br> <a id="ex22c"></a><br> <a id="ex23c"></a><br><br> <a id="ex24c"></a><br> <a id="ex25c"></a><br> <a id="ex26c"></a><br> </div> <script> let fruits111 = ["Apple", "Orange", "Pear"]; document.getElementById('ex19c').innerHTML = "original array: " + fruits111; document.getElementById('ex20c').innerHTML = "fruits array shift(): " + fruits111.shift(); // remove Apple document.getElementById('ex21c').innerHTML = "fruits array after shift(): " + fruits111; // Orange, Pear document.getElementById('ex22c').innerHTML = "fruits array second shift(): " + fruits111.shift()// remove Orange document.getElementById('ex23c').innerHTML = "fruits array after second shift(): " + fruits111; // Pear const fruits_aa = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById('ex24c').innerHTML = "original array: " + fruits_aa; document.getElementById("ex25c").innerHTML = "fruit shifted: " + fruits_aa.shift(); document.getElementById("ex26c").innerHTML = "second fruit shifted: " + fruits_aa.shift(); </script>
Syntax: array.slice(start, end)
parameters:
start : optional. Start position. Default is 0. Negative numbers select from the end of the array..
end : optional. End position. Default is last element.Negative numbers select from the end of the array.
The "slice() method" selects from a given start, up to a (not inclusive) given end. It does not change the original array.
Example
<div> <a id="ex27c"></a><br> <a id="ex28c"></a><br> <a id="ex29c"></a><br><br> <a id="ex30c"></a><br> <a id="ex31c"></a><br> <a id="ex32c"></a><br> <a id="ex33c"></a><br> </div> <script> const fruits3 = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; document.getElementById('ex27c').innerHTML = "before slice(): " + fruits3; const citrus = fruits3.slice(1, 3); document.getElementById('ex28c').innerHTML = "after slice(): " + citrus; const myBest = fruits3.slice(-3, -1); document.getElementById("ex29c").innerHTML = "after slice(): " + myBest; let arr6= ["t", "e", "s", "t"]; document.getElementById('ex30c').innerHTML = "original array: " + arr6 document.getElementById('ex31c').innerHTML = "first sliced items: " + arr6.slice(1, 3); document.getElementById('ex32c').innerHTML = "second sliced items: " + arr6.slice(-2); document.getElementById('ex33c').innerHTML = "third sliced items: " + arr6.slice(-3, -1); </script>
Syntax: array.some(function(value, index, arr), this)
parameters:
function :required. A function to run for each array element. .
value : required. The value of the current element.
index : optional. The index of the current element.
arr : optional. The array the current element belongs to.
this :optional. Default "undefined". A value passed to the function to be used as its "this" value.
The "some() method" returns true (and stops) if the function returns true for one of the array elements. It returns false if the function returns false for all of the array elements. The "some() method" does not execute the function for empty array elements and does not change the original array.
Example
Click the button to test if any array elements has a higher value than the input.
Input:
Values higher:
<div> <p id="ex34c"></p> <p id="ex35c"></p><br> <p>Click the button to test if any array elements has a higher value than the input.</p> <p id="ex36c"></p> <p>Input: <input type="number" id="thisToCheck" value="15"></p> <button onclick="myF()">test</button> <p>Values higher: <span id="ex37c"></span></p> </div> <script> const ages_zz = [3, 10, 18, 20]; document.getElementById('ex34c').innerHTML = "original array - ages: " + ages_zz; document.getElementById("ex35c").innerHTML = ages_zz.some(checkAdult); function checkAdult(age) { return age > 18; } const numbers22 = [4, 12, 16, 20]; document.getElementById('ex36c').innerHTML = "original array - numbers: " + numbers22; function checkValue(x) { return x > document.getElementById("thisToCheck").value; } function myF() { document.getElementById("ex37c").innerHTML = numbers22.some(checkValue); } </script>
Syntax: array.sort(compareFunction)
parameters:
compareFunction : optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments: function(a, b){return a-b}. When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Example: the sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value).
The "sort()" overwrites the original array and sorts the elements as strings in alphabetical and ascending order.
Example
<div> <p id="ex38c"></p> <p id="ex39c"></p> <p id="ex40c"></p> <p id="ex1d"></p><br> <p id="ex2d"></p> <p id="ex3d"></p> <p id="ex4d"></p> <p id="ex5d"></p> <p id="ex6d"></p><br> <p id="ex7d"></p> </div> <script> const fruits_ww = [" Banana", " Orange", " Apple", " Mango"]; document.getElementById('ex38c').innerHTML = "original array: " + fruits_ww; document.getElementById("ex39c").innerHTML = "sort without function: " + fruits_ww.sort(); fruits_ww.sort(); document.getElementById("ex40c").innerHTML = "sort without function: " + fruits_ww; fruits_ww.reverse(); document.getElementById("ex1d").innerHTML = "reverse the order" + fruits_ww; const points = [40, 100, 1, 5, 25, 10]; document.getElementById('ex2d').innerHTML = "original array: " + points; points.sort(function(a, b){return a-b}); document.getElementById("ex3d").innerHTML = "sorted array from low to high: " + points; points.sort(function(a, b){return b-a}); document.getElementById("ex4d").innerHTML = "sorted array from high to low: " + points; // Sort the numbers in ascending order: points.sort(function(a, b){return a-b}); // points[0] is now the lowest value: document.getElementById("ex5d").innerHTML = "lowest value: " + points[0]; // Sort the numbers in descending order: points.sort(function(a, b){return b-a}); // points[0] is now the highest value: document.getElementById("ex6d").innerHTML = "highest value: " + points[0]; function compareNumeric(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; } let arr9 = [ 1, 2, 15 ]; arr9.sort(compareNumeric); document.getElementById('ex7d').innerHTML = "sort array: " + arr9; </script>
Syntax: array.splice(index, howmany, item1, ....., itemX)
parameters:
index :required. Negative value defines the position from the end of the array.
howmany : optional. Number of items to be removed.
item1, ..., itemX : optional. New elements(s) to be added..
This method overwrites the original array.
Example
<div> <a id="ex8d"></a><br> <a id="ex9d"></a><br><br> <a id="ex10d"></a><br> <a id="ex11d"></a><br><br> <a id="ex12d"></a><br> <a id="ex13d"></a><br> <a id="ex14d"></a><br> <a id="ex15d"></a><br> </div> <script> let arr4 = ["I", "study", "JavaScript", "right", "now"]; document.getElementById('ex8d').innerHTML = "before splice(): " + arr4; arr4.splice(0, 3, "Let's", "dance"); document.getElementById('ex9d').innerHTML = "after splice(): " + arr4; let arr5 = ["I", "study", "JavaScript", "right", "now"]; document.getElementById('ex10d').innerHTML = "original array: " + arr5; let removed = arr5.splice(0, 2); document.getElementById('ex11d').innerHTML = "removed elements: " + removed; let garden_pp = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex12d").innerHTML = "original array: " + garden_pp; // At position 2, add 2 elements: garden_pp.splice(2, 0, "Lemon", "Kiwi"); document.getElementById("ex13d").innerHTML = "new array without removing: " + garden_pp; // At position 2, remove 2 items: garden_pp.splice(2, 2); document.getElementById("ex14d").innerHTML = "new array with removing: " + garden_pp; // // At position 2, add 2 elements, remove 1: garden_pp.splice(2, 1, "Lemon", "Kiwi"); document.getElementById("ex15d").innerHTML = "new array without/with removing: " +garden_pp; </script>
Syntax: array.toString()
parameters: none.
The "toString() method" returns a string with array values separated by commas. It does not change the original array.
Every JavaScript object has a toString() method. The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string. Normally, you will not use it in your own code.
Example
<div> <a id="ex16d"></a><br> <a id="ex17d"></a><br> <a id="ex18d"></a><br> </div> <script> var fruits11 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex16d").innerHTML = "original array: " + JSON.stringify(fruits11); document.getElementById("ex17d").innerHTML = "fruits to string: " + fruits11.toString(); let text_mm = fruits11.toString(); document.getElementById("ex18d").innerHTML = "fruits to string: " + text_mm; </script>
Syntax: array.unshift(item1, item2, ..., itemX)
parameters:
item1, item2, ..., itemX : The item(s) to add to the array. Minimum one item is required.
The "unshift() method" overwrites the original array.
Example
<div> <a id="ex19d"></a><br><br> <button class="spec" onclick="myFunction10()">try it</button><br><br> <a id="ex20d"></a><br><br> <a id="ex21d"></a><br> <a id="ex22d"></a><br> </div> <script> var fruits18 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex19d").innerHTML = "before unshift(): " + fruits18; function myFunction10() { fruits18.unshift("Lemon"); document.getElementById("ex20d").innerHTML = "after unshift(): " + fruits18; } let fruits_ll = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex21d").innerHTML = "original array: " + fruits_ll; fruits_ll.unshift("Lemon", "Pineapple"); document.getElementById("ex22d").innerHTML = "after unshift() new array: " + fruits_ll; </script>
Syntax: array.valueOf()
parameters: none.
The "valueOf() method" does not change the original array.
Example
<div> <p>Click the button to return the primitive value of the string object.</p> <button onclick="myFunctionC()">Try it</button><br> <a id="ex23d"></a><br><br> <a id="ex24d"></a><br> </div> <script> function myFunctionC() { var str = "Hello World!"; var res = str.valueOf(); document.getElementById("ex23d").innerHTML = res; } const fruits_jj = ["Banana", "Orange", "Apple", "Mango"]; const myArray_jj = fruits_jj.valueOf(); document.getElementById("ex24d").innerHTML = "primitive value of array: " + myArray_jj; </script>
Example
<div> <a id="ex25d"></a> </div> <script> var fruits7, text, fLen, i; fruits7 = ["Banana", "Orange", "Apple", "Mango"]; fruits7[6] = "Lemon"; fLen = fruits7.length; text = ""; for (i = 0; i < fLen; i++) { text += fruits7[i] + " , "; } document.getElementById("ex25d").innerHTML = text; </script>
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator "delete". Deleting elements leaves undefined holes in an array.
Example
<div> <a id="ex26d"></a><br> <a id="ex27d"></a><br><br> <a id="ex28d"></a><br> <a id="ex29d"></a><br> <a id="ex30d"></a><br> </div> <script> var fruits19 = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("ex26d").innerHTML = "Before deleting: the first fruit is: " + fruits19[0]; delete fruits19[0]; document.getElementById("ex27d").innerHTML = "After deleting, the first fruit is: " + fruits19[0]; let arr12 = ["I", "go", "home"]; document.getElementById('ex28d').innerHTML = "original array: " + arr12; delete arr12[1]; document.getElementById('ex29d').innerHTML = "second element deleted: " + arr12[1]; document.getElementById('ex30d').innerHTML = "array length: " + arr12.length; </script>
Example
<div> <a id="ex31d"></a><br> <a id="ex32d"></a><br> <a id="ex33d"></a><br> <a id="ex34d"></a><br> </div> <script> let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"} ]; let user = users.find(item => item.id == 1); document.getElementById('ex31d').innerHTML += "users: " + JSON.stringify(users); document.getElementById('ex32d').innerHTML = "find user with id 1: " + user.name; let someUsers = users.filter(item => item.id < 3); document.getElementById('ex33d').innerHTML = "some users: " + JSON.stringify(someUsers); document.getElementById('ex34d').innerHTML = "length of filtering array (someUsers): " + someUsers.length; </script>
Filter out all falsy values from an array: using this function you will be able to filter out all falsy values(0, null, undefined, false) from an array.
Example - code
const removeFalsyValues = arr => arr.filter(Boolean); removeFalsyValues([0, 'a', 1, NaN, true, 5, undefined, false]); // ['a', 1, true, 5]
const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5]; const filteredArr = arr.filter((value) => !!value); console.log(filteredArr); // output: [1, 2, 3, 5]
const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5]; const filteredArr = arr.filter(Boolean); console.log(filteredArr); // output: [1, 2, 3, 5]
solution 1: sort the array first and then the last item of the array is the maximum value.
<div> <p id="ex35d"></p> <p id="ex36d"></p> <p id="ex37d"></p> <p id="ex38d"></p> </div> <script> const array = [ 1, 10, -19, 2, 7, 100 ] document.getElementById("ex35d").innerHTML = "original array: " + array; var x = array.sort((a, b) => a - b) document.getElementById("ex36d").innerText = "sorted array: " + x; document.getElementById("ex37d").innerText = "max value is :" + array[array.length-1]; document.getElementById("ex38d").innerText = "min value is :" + array[0]; </script>
solution 2: handle it with “Math.max”.
<div> <p id="ex39d"></p> <p id="ex40d"></p> <p id="ex1e"></p> </div> <script> const array_2 = [ 1, 10, -19, 2, 7, 100 ] document.getElementById("ex39d").innerHTML = "array: " + array_2; document.getElementById("ex40d").innerHTML = "max value: " + Math.max(...array_2); document.getElementById("ex1e").innerHTML = "min value: " + Math.min(...array_2); </script>
Example
<div> <p id="ex2e"></p> <p id="ex3e"></p> <p id="ex4e"></p> </div> <script> const array_3 = [ 1, 10, -19, 2, 7, 100 ] document.getElementById("ex2e").innerHTML = "array: " + array_3; const sum = array.reduce((sum, num) => sum + num) // 101 document.getElementById("ex3e").innerHTML = "sum of array (reduce(sum, num)): " + sum; </script>
Example
<div> <p id="ex4e"></p> <p id="ex5e"></p> <p id="ex6e"></p> <p id="ex7e"></p> </div> <script> const array_4 = [ 'fatfish', 'fish', 24, 'hello', 'world' ] document.getElementById("ex4e").innerHTML = "original array: " + array_4; const getRandomValue = (array_4) => { return array_4[ Math.floor(Math.random() * array_4.length) ] } document.getElementById("ex5e").innerHTML = "random value of array: " + getRandomValue(array_4); document.getElementById("ex6e").innerHTML = "random value of array: " + getRandomValue(array_4); document.getElementById("ex7e").innerHTML = "random value of array: " + getRandomValue(array_4); </script>
Example
<div> <p id="ex8e"></p> <p id="ex9e"></p> <p id="ex10e"></p> <p id="ex11e"></p> </div> <script> const prizes = [ '📱', '🍫', '🍵', '🍔' ] document.getElementById("ex8e").innerHTML = "prizes: " + prizes; prizes.sort(() => 0.5 - Math.random()) document.getElementById("ex9e").innerHTML = "random sorting of prizes: " + prizes; console.log(prizes) // ['📱', '🍔', '🍫', '🍵'] prizes.sort(() => 0.5 - Math.random()) document.getElementById("ex10e").innerHTML = "random sorting of prizes: " + prizes; console.log(prizes) // ['🍫', '🍔', '📱', '🍵'] prizes.sort(() => 0.3 - Math.random()) document.getElementById("ex11e").innerHTML = "random sorting of prizes: " + prizes; </script>
JavaScript is very tricky when it comes to its built-in sort method. It doesn't handle numbers well, so this function is a simple way of sorting your array.
Example - code
const sort = arr => arr.sort((a, b) => a - b); //example sort([1, 5, 2, 4, 3]); // Result: [1, 2, 3, 4, 5]
const numbers = array => numbers.sort((a, b) => a - b); //example const numbers = [10, 5, 11]; // => [5, 10, 11]
const points = array => points.sort(function(a, b){return b - a}); //example const points = [40, 100, 1, 5, 25, 10]; //result: 100,40,25,10,5,1;
solution 1:
<div> <p id="ex12e"></p> <p id="ex13e"></p> </div> <script> const array_5 = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ] document.getElementById("ex12e").innerText = "array is: " + JSON.stringify(array_5); const flattenArray = (array) => { return array.reduce((res, it) => { return res.concat(Array.isArray(it) ? flattenArray(it) : it) }, []) } document.getElementById("ex13e").innerHTML = "flattened array: " + flattenArray(array_5); console.log(flattenArray(array)) </script>
solution 2:
Example
<div> <p id="ex14e"></p> <p id="ex15e"></p> </div> <script> const array_6 = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ] document.getElementById("ex14e").innerText = "array is: " + "[ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]"; document.getElementById("ex15e").innerHTML = "flattened array: " + array.flat(Infinity); console.log(array.flat(Infinity)) </script>
Flattening an array means converting a multi-dimension array to one-dimensional array.
Example - code
const flatten = array => [].concat(...array); // flattens an array(doesn't flatten deeply)
const flattenDeep = arr => arr.reduce((fArr, item) => fArr.concat(Array.isArray(item) ? flatten(item) : item), []);
const arr1 = [0, 1, 2, [3, 4]]; console.log(arr1.flat()); // expected output: [0, 1, 2, 3, 4]
In the past, we always used the “indexOf” method to check if the array contained a value. If the value returned by “indexOf” is greater than -1, it means that there is one.
Example
<div> <p id="ex16e"></p> <p id="ex17e"></p> <p id="ex18e"></p> <p id="ex19e"></p> <p id="ex20e"></p> </div> <script> const array_7 = [ 'fatfish', 'hello', 'world', 24 ] document.getElementById("ex16e").innerText = "array is: " + "[ 'fatfish', 'hello', 'world', 24 ]"; document.getElementById("ex17e").innerHTML = "index of 'fatfish': " + array_7.indexOf("fatfish"); document.getElementById("ex18e").innerHTML = "index of 'medium': " + array_7.indexOf("medium"); document.getElementById("ex19e").innerHTML = "index of '24': " + array_7.indexOf(24); document.getElementById("ex20e").innerHTML = "index of string '24': " + array_7.indexOf("24"); </script>
But now the data is more complex. We will not be able to directly confirm whether "fatfish" exists in the array through the indexOf method. Fortunately, the findIndex method is provided in ES6.
Example
<div> <p id="ex21e"></p> <p id="ex22e"></p> <p id="ex23e"></p> </div> <script> const array_8 = [{name: 'fatfish'}, {name: 'hello'}, {name: 'world'},] document.getElementById("ex21e").innerText = "array is: " + JSON.stringify(array_8); const index = array_8.findIndex((it) => it.name === 'fatfish') document.getElementById("ex22e").innerHTML = "index of 'fatfish': " + index; const index1 = array_8.findIndex((it) => it.name === 'world') document.getElementById("ex23e").innerHTML = "index of 'world': " + index1; </script>
A clean and easy ways to check if a variable is an array.
Example - code
const isArray = (arr) => Array.isArray(arr); console.log(isArray([1, 2, 3])); // true console.log(isArray({ name: 'Ovi' })); // false console.log(isArray('Hello World')); // false
const ratings = [1, 2, 3, 4, 5]; const vote = { user: 'John Doe', rating: 5 }; const str = "It isn't an array"; console.log(Array.isArray(ratings)); // true console.log(Array.isArray(vote)); // false console.log(Array.isArray(str)); // false
const ratings = [1, 2, 3, 4, 5]; const vote = { user: 'John Doe', rating: 5 }; const str = "It isn't an array"; console.log(ratings instanceof Array); // true console.log(vote instanceof Array); // false console.log(str instanceof Array); // false
Use the “isArray” method and check if the length of the array is higher than 0. In this way, it can be checked if the array is empty.
Example - code
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; /examples isNotEmpty([1, 2, 3]); // Result: true isNotEmpty([]); // Result: false
const isEmpty = arr => !Array.isArray(arr) || arr.length === 0; // examples isEmpty([]); // true isEmpty([1, 2, 3]); // false
const myArray = arr => Array.isArray(arr) && arr.length !==0;
such a judgment method can achieve the purpose of conditional judgment, but it seems very cumbersome.
Example
<div> <p id="ex24e"></p> <p id="ex25e"></p> </div> <script> const value = 'fatfish' document.getElementById("ex24e").innerHTML = "value is: " + value; if (value === 'fatfish' || value === 'medium' || value === 'fe') { document.getElementById("ex25e").innerHTML = "judgment is: " + "hello world"; } </script>
the includes method can be used to make the code simpler or even more extensible
Example
<div> <p id="ex26e"></p> <p id="ex27e"></p> </div> <script> const conditions = [ 'fatfish', 'medium', 'fe' ]; document.getElementById("ex26e").innerHTML = "conditions = [ 'fatfish', 'medium', 'fe' ]"; const value_a = 'fatfish' if (conditions.includes(value_a)) { document.getElementById("ex27e").innerHTML = 'hello world'; } </script>
Example
<div> <p id="ex28e"></p> <p id="ex29e"></p> <p id="ex30e"></p> </div> <script> var fruits11 = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"]; document.getElementById("ex28e").innerHTML = "array: " + fruits11; // First method var uniqueFruits = Array.from(new Set(fruits11)); document.getElementById("ex29e").innerHTML = "unique fruits, solution 1 : " + uniqueFruits; // Second method var uniqueFruits2 = [...new Set(fruits11)]; document.getElementById("ex30e").innerHTML = "unique fruits, solution 2 : " + uniqueFruits2; </script>
Remove duplicates from an array: this can be done in different ways
Example - code
const removeDuplicates = arr => arr.filter ((item, index) => index === arr.indexOf(item)); // using "filter" and "indexOf"
const removeDuplicates1 = array => [...new Set(array)]; // use set data structures and spread operator
const removeDuplicates2 = array => Array.from(new Set(array)); // use set data structures and Array.from method
Example
<div> <p id="ex31e"></p> <p id="ex32e"></p> <p id="ex33e"></p> </div> <script> var fruits_a = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"]; document.getElementById("ex31e").innerHTML = " original array: " + fruits_a; fruits_a.splice(0, 2, "potato", "tomato"); document.getElementById("ex32e").innerHTML = " new array: " + fruits_a; </script>
Example
<div> <p id="ex33e"></p> <p id="ex34e"></p> <p id="ex35e"></p> </div> <script> var friends = [ { name: "John", age: 22 }, { name: "Peter", age: 23 }, { name: "Mark", age: 24 }, { name: "Maria", age: 22 }, { name: "Monica", age: 21 }, { name: "Martha", age: 19 }, ] document.getElementById("ex33e").innerHTML = "array is: " + JSON.stringify(friends); var friendsNames = Array.from(friends, ({name}) => name); document.getElementById("ex34e").innerHTML = "names of friends:" + friendsNames; var friendsAges = Array.from(friends, ({age}) => age); document.getElementById("ex35e").innerHTML = "ages of friends:" + friendsAges; </script>
Example
<div> <p id="ex36e"></p> <p id="ex37e"></p> <p id="ex38e"></p> </div> <script> var fruit_aa = ["banana", "apple", "orange", "watermelon"]; document.getElementById("ex36e").innerHTML = "array: " + fruit_aa; var fruitObj = { ...fruit_aa }; document.getElementById("ex37e").innerHTML = "converting to object: " + JSON.stringify(fruitObj); </script>
You can spread the elements of an array into another array by using the spread operator "...".
longhand
// joining arrays const odd = [1, 3, 5]; const nums = [2 ,4 , 6].concat(odd); // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = arr.slice()
shorthand
// joining arrays const odd = [1, 3, 5 ]; const nums = [2 ,4 , 6, ...odd]; console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [...arr];
base
const nums1 = [1, 2, 3]; const nums2 = [4, 5, 6];
longhand
let newArray = nums1.concat(nums2);
shorthand
numbers = [...numbers, 4, 5];
There are a couple of ways to merge arrays. One of them is using the “concat” method. Another one is using the spread operator (”…”). We can also eliminate duplicates from the final array using the “Set” object. Also, Array.concat method with spread operator can be used.
Example - code
// Merge but don't remove the duplications const merge = (a, b) => a.concat(b); const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications const merge = [...new Set(a.concat(b))]; const merge = [...new Set([...a, ...b])];
// Merge but don't remove the duplications nums1.push(...nums2, ...nums3); console.log(nums1);
Using this function, common items from arrays can be found, and any number of arrays can be passed. The function will return the common items and a blank array if the arrays don’t have any items in common.
Example - code
const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v))); // Examples getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3] getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
const arr1 = [4,5,6,7]; const arr2 = [4,6,1,3]; const intersection = arr1.filter(val=>arr2.includes(val)); console.log(intersection); // [4,6]
const arr1 = [4,5,6,7]; const arr2 = [4,6,1,3]; const intersection = arr1.filter(val=>arr2.indexOf(val)<-1); console.log(intersection); // [4,6]
A one-liner implementation of range using Array.from method generates a range from start to end (exclusive). It also takes an optional step parameter.
Example - code
const range = (start, end, step = 1) => Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step);
const range = (start, stop, step = 1) => Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
[...Array(N)].map((_, i) => from + i * step);
This situation is a regular one, when an array of objects has to be grouped by a key. This simple trick allows to do that in a single line!
Example - code
const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {}) // Example const cars = [ { brand: 'audi', model: 'q8', year: '2019' }, { brand: 'audi', model: 'rs7', year: '2020' }, { brand: 'ford', model: 'mustang', year: '2019' }, { brand: 'ford', model: 'explorer', year: '2020' }, { brand: 'bmw', model: 'x7', year: '2020' }, { brand: 'kia', model: 'optima', year: '2012'} ]; groupBy(cars, 'brand') // { // audi: [ // { brand: 'audi', model: 'q8', year: '2019' }, // { brand: 'audi', model: 'rs7', year: '2020' } // ], // bmw: [ // { brand: 'bmw', model: 'x7', year: '2020' } // ], // ford: [ // { brand: 'ford', model: 'mustang', year: '2019' }, // { brand: 'ford', model: 'explorer', year: '2020' } // ], // kia: [ // { brand: 'kia', model: 'optima', year: '2012'} // ] // }
const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {}) // Example const cars = [ { brand: 'audi', model: 'q8', year: '2019' }, { brand: 'audi', model: 'rs7', year: '2020' }, { brand: 'ford', model: 'mustang', year: '2019' }, { brand: 'ford', model: 'explorer', year: '2020' }, { brand: 'bmw', model: 'x7', year: '2020' }, { brand: 'kia', model: 'optima', year: '2012'} ]; groupBy(cars, 'brand') // { // audi: [ // { brand: 'audi', model: 'q8', year: '2019' }, // { brand: 'audi', model: 'rs7', year: '2020' } // ], // bmw: [ // { brand: 'bmw', model: 'x7', year: '2020' } // ], // ford: [ // { brand: 'ford', model: 'mustang', year: '2019' }, // { brand: 'ford', model: 'explorer', year: '2020' } // ], // kia: [ // { brand: 'kia', model: 'optima', year: '2012'} // ] // }
code: <div> <div style="margin-left: 3vw;" id="array"></div> <div style="margin-left: 3vw;" id="array1"></div> </div> <script> let arrayOfImages = []; // Push the URLs to three images to arrayOfImages arrayOfImages.push('1.jpg'); arrayOfImages.push('2.jpg'); arrayOfImages.push('3.jpg'); // Output arrayOfImages to the console document.getElementById("array").innerHTML = arrayOfImages; let arrayOfImages_a = []; // Push the URLs to three images to arrayOfImages arrayOfImages_a.push('1.jpg', 'title 1', '768px', '1024px'); arrayOfImages_a.push('2.jpg', 'title 2', '720px', '1280px'); arrayOfImages_a.push('3.jpg', 'title 3', '1080px', '1920px'); // Output arrayOfImages to the console document.getElementById("array1").innerHTML = arrayOfImages_a; </script>
<div style="margin-left: 3vw;" id="array2"></div> <script> let arrayImages = []; let myImage = new Image(200, 200); myImage.src = "../pics/1.jpg"; arrayImages.push(myImage); console.log(arrayImages); document.body.appendChild(arrayImages[0]); </script>
<div> <!-- <body onload="makeImage();"> --> <div class="contents" id="content"> <button onclick="nextImage()">Next Image</button> </div> </div> <script> var images = ["../pics/1.jpg", "../pics/2.jpg", "../pics/3.jpg", "../pics/4.jpg", "../pics/5.jpg", "../pics/vangogh.jpg"]; var index_a = 0; function makeImage() { var img = document.createElement('img') img.src = images[index_a]; document.getElementById('content').appendChild(img); } function nextImage(){ var img = document.getElementById('content').getElementsByTagName('img')[0] index_a++; index_a = index_a % images.length; img.src = images[index_a]; } </script>
<div> <img name="holiday" id="holiday" src="1.jpg" width="250" height="200"><br> <a href="JavaScript: next_frame()">Next Frame </a> <br> <a href="JavaScript: last_frame()">Previous Frame </a> <br> </div> <script> var demoImages = new Array("../pics/1.jpg", "../pics/2.jpg", "../pics/3.jpg", "../pics/4.jpg"); index_no = 0; function next_frame(){ index_no++; if(index_no < demoImages.length){ document.images["holiday"].src = demoImages[index_no]; } else{ index_no = 0; document.images["holiday"].src = demoImages[index_no]; } } function last_frame(){ index_no--; if(index_no >= 0){ document.images["holiday"].src = demoImages[index_no]; } else{ index_no = demoImages.length - 1; document.images["holiday"].src = demoImages[index_no]; } } </script>
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
const array1 = ['a', 'b', 'c', 'd', 'e']; // copy to index 0 the element at index 3 console.log(array1.copyWithin(0, 3, 4)); // expected output: Array ["d", "b", "c", "d", "e"] // copy to index 1 all elements from index 3 to the end console.log(array1.copyWithin(1, 3)); // expected output: Array ["d", "d", "e", "d", "e"]
const array1 = ['a', 'b', 'c']; const iterator1 = array1.entries(); console.log(iterator1.next().value); // expected output: Array [0, "a"] console.log(iterator1.next().value); // expected output: Array [1, "b"]
const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold)); // expected output: true
const array1 = [1, 2, 3, 4]; // fill with 0 from position 2 until position 4 console.log(array1.fill(0, 2, 4)); // expected output: [1, 2, 0, 0] // fill with 5 from position 1 console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5] console.log(array1.fill(6)); // expected output: [6, 6, 6, 6]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // expected output: 12
const array1 = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; console.log(array1.findIndex(isLargeNumber)); // expected output: 3
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // expected output: "a" // expected output: "b" // expected output: "c"
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]
const array1 = [1, 2, 3]; console.log(array1.includes(2)); // expected output: true const pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4 console.log(beasts.indexOf('giraffe')); // expected output: -1
const array1 = ['a', 'b', 'c']; const iterator1 = array1[Symbol.iterator](); for (const value of iterator1) { console.log(value); } // expected output: "a" // expected output: "b" // expected output: "c"
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // expected output: "Fire,Air,Water" console.log(elements.join('')); // expected output: "FireAirWater" console.log(elements.join('-')); // expected output: "Fire-Air-Water"
const array1 = ['a', 'b', 'c']; const iterator = array1.keys(); for (const key of iterator) { console.log(key); } // expected output: 0 // expected output: 1 // expected output: 2
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); // expected output: 3 console.log(animals.lastIndexOf('Tiger')); // expected output: 1
const clothing = ['shoes', 'shirts', 'socks', 'sweaters']; console.log(clothing.length); // expected output: 4
const array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32]
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // expected output: "tomato" console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"]
const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push('chickens', 'cats', 'dogs'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue) ); console.log(array1); // expected output: Array [4, 5, 2, 3, 0, 1]
const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"] const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"] // Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]
const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1); // expected output: Array [2, 3] console.log(firstElement); // expected output: 1
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]
const array = [1, 2, 3, 4, 5]; // checks whether an element is even const even = (element) => element % 2 === 0; console.log(array.some(even)); // expected output: true
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]
const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // replaces 1 element at index 4 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"]
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]; const localeString = array1.toLocaleString('en', { timeZone: 'UTC' }); console.log(localeString); // expected output: "1,a,12/21/1997, 2:12:00 PM", // This assumes "en" locale and UTC timezone - your results may vary
const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // expected output: "1,2,a,1a"
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // expected output: 5 console.log(array1); // expected output: Array [4, 5, 1, 2, 3]
const array1 = ['a', 'b', 'c']; const iterator = array1.values(); for (const value of iterator) { console.log(value); } // expected output: "a" // expected output: "b" // expected output: "c"
// create an ArrayBuffer with a size in bytes const buffer = new ArrayBuffer(8); // use byteLength to check the size const bytes = buffer.byteLength; console.log(bytes); // expected output: 8
// create an ArrayBuffer with a size in bytes const buffer = new ArrayBuffer(8); console.log(buffer.byteLength); // expected output: 8
// create an ArrayBuffer with a size in bytes const buffer = new ArrayBuffer(16); console.log(ArrayBuffer.isView(new Int32Array())); // expected output: true
// create an ArrayBuffer with a size in bytes const buffer = new ArrayBuffer(16); const int32View = new Int32Array(buffer); // produces Int32Array [0, 0, 0, 0] int32View[1] = 42; const sliced = new Int32Array(buffer.slice(4, 12)); // produces Int32Array [42, 0] console.log(sliced[0]); // expected output: 42
let arr = new Array(); let arr = []; let fruits = ["Apple", "Orange", "Plum"]; alert( fruits[0] ); // Apple alert( fruits[1] ); // Orange alert( fruits[2] ); // Plum fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"] fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"] let fruits = ["Apple", "Orange", "Plum"]; alert( fruits.length ); // 3 alert( fruits ); // Apple,Orange,Plum // mix of values let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ]; // get the object at index 1 and then show its name alert( arr[1].name ); // John // get the function at index 3 and run it arr[3](); // hello
let fruits = ["Apple", "Orange", "Plum"]; alert( fruits[fruits.length-1] ); // Plum // same as fruits[fruits.length-1] alert( fruits.at(-1) ); // Plum
let fruits = ["Apple", "Orange", "Pear"]; alert( fruits.pop() ); // remove "Pear" and alert it alert( fruits ); // Apple, Orange fruits.push("Pear"); alert( fruits ); // Apple, Orange, Pear let fruits = ["Apple", "Orange", "Pear"]; alert( fruits.shift() ); // remove Apple and alert it alert( fruits ); // Orange, Pear fruits.unshift('Apple'); alert( fruits ); // Apple, Orange, Pear let fruits = ["Apple"]; fruits.push("Orange", "Peach"); fruits.unshift("Pineapple", "Lemon"); // ["Pineapple", "Lemon", "Apple", "Orange", "Peach"] alert( fruits );
let fruits = ["Banana"] let arr = fruits; // copy by reference (two variables reference the same array) alert( arr === fruits ); // true arr.push("Pear"); // modify the array by reference alert( fruits ); // Banana, Pear - 2 items now
let arr = ["Apple", "Orange", "Pear"]; for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } let fruits = ["Apple", "Orange", "Plum"]; // iterates over array elements for (let fruit of fruits) { alert( fruit ); } let arr = ["Apple", "Orange", "Pear"]; for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear }
let fruits = []; fruits[123] = "Apple"; alert( fruits.length ); // 124 let arr = [1, 2, 3, 4, 5]; arr.length = 2; // truncate to 2 elements alert( arr ); // [1, 2] arr.length = 5; // return length back alert( arr[3] ); // undefined: the values do not return
let arr = new Array("Apple", "Pear", "etc"); let arr = new Array(2); // will it create an array of [2] ? alert( arr[0] ); // undefined! no elements. alert( arr.length ); // length 2
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; alert( matrix[1][1] ); // 5, the central element
let arr = [1, 2, 3]; alert( arr ); // 1,2,3 alert( String(arr) === '1,2,3' ); // true alert( [] + 1 ); // "1" alert( [1] + 1 ); // "11" alert( [1,2] + 1 ); // "1,21"
alert( [] == [] ); // false alert( [0] == [0] ); // false alert( 0 == [] ); // true alert('0' == [] ); // false // after [] was converted to '' alert( 0 == '' ); // true, as '' becomes converted to number 0 alert('0' == '' ); // false, no type conversion, different strings
arr.splice(start[, deleteCount, elem1, ..., elemN]) let arr = ["I", "study", "JavaScript"]; arr.splice(1, 1); // from index 1 remove 1 element alert( arr ); // ["I", "JavaScript"] let arr = ["I", "study", "JavaScript", "right", "now"]; // remove 3 first elements and replace them with another arr.splice(0, 3, "Let's", "dance"); alert( arr ) // now ["Let's", "dance", "right", "now"] let arr = ["I", "study", "JavaScript", "right", "now"]; // remove 2 first elements let removed = arr.splice(0, 2); alert( removed ); // "I", "study" <-- array of removed elements let arr = ["I", "study", "JavaScript"]; // from index 2 // delete 0 // then insert "complex" and "language" arr.splice(2, 0, "complex", "language"); alert( arr ); // "I", "study", "complex", "language", "JavaScript" let arr = [1, 2, 5]; // from index -1 (one step from the end) // delete 0 elements, // then insert 3 and 4 arr.splice(-1, 0, 3, 4); alert( arr ); // 1,2,3,4,5
arr.slice([start], [end]) let arr = ["t", "e", "s", "t"]; alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3) alert( arr.slice(-2) ); // s,t (copy from -2 till the end)
arr.concat(arg1, arg2...) let arr = [1, 2]; // create an array from: arr and [3,4] alert( arr.concat([3, 4]) ); // 1,2,3,4 // create an array from: arr and [3,4] and [5,6] alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6 // create an array from: arr and [3,4], then add values 5 and 6 alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6 let arr = [1, 2]; let arrayLike = { 0: "something", length: 1 }; alert( arr.concat(arrayLike) ); // 1,2,[object Object]
arr.forEach(function(item, index, array) { // ... do something with item }); // for each element call alert ["Bilbo", "Gandalf", "Nazgul"].forEach(alert); ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => { alert(`${item} is at index ${index} in ${array}`); });
let arr = [1, 0, false]; alert( arr.indexOf(0) ); // 1 alert( arr.indexOf(false) ); // 2 alert( arr.indexOf(null) ); // -1 alert( arr.includes(1) ); // true let fruits = ['Apple', 'Orange', 'Apple'] alert( fruits.indexOf('Apple') ); // 0 (first Apple) alert( fruits.lastIndexOf('Apple') ); // 2 (last Apple)
let result = arr.find(function(item, index, array) { // if true is returned, item is returned and iteration is stopped // for falsy scenario returns undefined }); let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"} ]; let user = users.find(item => item.id == 1); alert(user.name); // John let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"}, {id: 4, name: "John"} ]; // Find the index of the first John alert(users.findIndex(user => user.name == 'John')); // 0 // Find the index of the last John alert(users.findLastIndex(user => user.name == 'John')); // 3
let results = arr.filter(function(item, index, array) { // if true item is pushed to results and the iteration continues // returns empty array if nothing found }); let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "Mary"} ]; // returns array of the first two users let someUsers = users.filter(item => item.id < 3); alert(someUsers.length); // 2
let result = arr.map(function(item, index, array) { // returns the new value instead of item }); let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); alert(lengths); // 5,7,6
let arr = [ 1, 2, 15 ]; // the method reorders the content of arr arr.sort(); alert( arr ); // 1, 15, 2 function compareNumeric(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; } let arr = [ 1, 2, 15 ]; arr.sort(compareNumeric); alert(arr); // 1, 2, 15
let arr = [1, 2, 3, 4, 5]; arr.reverse(); alert( arr ); // 5,4,3,2,1
let names = 'Bilbo, Gandalf, Nazgul'; let arr = names.split(', '); for (let name of arr) { alert( `A message to ${name}.` ); // \A message to Bilbo (and other names) } let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); alert(arr); // Bilbo, Gandalf let arr = ['Bilbo', 'Gandalf', 'Nazgul']; let str = arr.join(';'); // glue the array into a string using ; alert( str ); // Bilbo;Gandalf;Nazgul
let value = arr.reduce(function(accumulator, item, index, array) { // ... }, [initial]); let arr = [1, 2, 3, 4, 5]; let result = arr.reduce((sum, current) => sum + current, 0); alert(result); // 15 let arr = [1, 2, 3, 4, 5]; // removed initial value from reduce (no 0) let result = arr.reduce((sum, current) => sum + current); alert( result ); // 15