Learning JavaScript Array Methods

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

In previous learning-note post, Understanding JavaScript Arrays some basic features of JavaScript arrays : syntax, creating an array, accessing array elements, recognizing an array, looping through an array elements and basic adding/deleting elements were discussed.

From JS data type & structure perspective, JS Arrays can be compared with ‘String‘ as both consist of sequence of elements that can be accessed via index number. JS strings are immutable meaning original elements of a string can’t be modified once it is created (a sub-string can be created from the original). On the other hand, JS arrays are mutable meaning original arrays (not an array copy) can be modified using array method().

In this learning-note post, we will explore array manipulation using array method(). The real strength of JS arrays are in built-in methods and properties which we will discuss using simple examples. A more detail complete list of array properties & methods and their use cases is available on Array – MDN Documents.

Tip: In this post JS an array method is referred as method(). Proper way to write an array is Array.prototype.method(), where Array.prototype refers to the Array object itself.

Mutator Methods

These are methods that modify the original elements of an JS array. In this section we will look at methods that add,  remove, reverse, replace, and modify elements in an array.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" target="_blank" rel="noopener">isArray()</a>

Returns true if a variable is an array, if not false.

In the previous learning-note Understanding JavaScript Arrays, we discussed how to recognize an array from an object using isArray() method. Lets revisiting the same example below:

// initialize myCar array with four items 
let myCar = [ "Toyota", "Corolla", 2018 ];

// proof if myCar is an array
Array.isArray(myCar); //OUTPUT => true

//checking with typeof
typeof(myCar); //OUTPUT => object

isArray() is a Boolean method which returns true if the value of an object variable is an array and returns false if the value of an object variable is not an array. In the example above, output of isArray(myCar) is true (line 5) confirming that myCar is an array.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" target="_blank" rel="noopener">pop()</a>

Removes the last element from an array and returns that element.

Lets revisit cars array that was used in the previous learning-note Understanding JavaScript Arrays with four car brand names as array items.

// basic syntax
arr.pop();

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

// pop() removes last item from an Array
cars.pop(); // OUTPUT => GM
//access cars Array
cars; //OUTPUT => (3) ["Toyota", "Ford", "Honda"]

In the example above, cars.pop() method was applied (line 8) on the cars array (line 5) to remove the last item "GM" from the array. When cars array was accessed (line 10), the output confirmed our modified cars array has now only 3 items and "GM" was removed.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift" target="_blank" rel="noopener">shift()</a>

Removes the first element from an array and returns that element.

Revisiting cars array example from previous section, lets remove the first element "Toyota" from the array using shift() method.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

//shift() removes first item of an Array
cars.shift(); // OUTPUT => Toyota
//access cars Array
cars; //OUTPUT => (3) ["Ford", "Honda", "GM"]

In the example above, Toyota was removed from index 0 position and the remaining three items were shifted by one index number. One of the drawbacks of this method is it changes original index position of array items. If maintaining the original index number is important then pop() method is to remove an item from an array.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank" rel="noopener">push()</a>

Adds one or more elements to the end of an array and returns the new length of the array.

Revisiting again cars array from previous section, lets add an item with "BMW" value using push() method at the end cars array. The push() method takes new item(s) as parameter of the function.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

// push() adds item at the end of Array
cars.push("BMW"); //OUTPUT => 5
//access cars Array
cars; //OUTPUT => (5) ["Toyota", "Ford", "Honda", "GM", "BMW"]

In the example above, a new value of "BMW" was added at the end of the array (index 4) using cars.push("BMW") and now its new length is 5 (line 5). To add multiple values, comma ( ,)separated values should be passed as function parameter (eg. cars.push("Lexus", "GM") to add at the index 5 & 6 position.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift" target="_blank" rel="noopener">unshift()</a>

Adds one or more elements to the front of an array and returns the new length of the array.

In cars array below, we will use unshift() method to add "Lexus" at the beginning of the array. The unshift() method takes values as parameter(s) of the function.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

// unshift() adds item to beginning if an Array
cars.unshift("Lexus"); // OUTPUT => 5
//access cars Array
cars; //OUTPUT => (5) ["Lexus", "Toyota", "Ford", "Honda", "GM"]

In the example above, "Lexus" was added with cars.unshift("Lexus") at index 0 position (line 7) which shifts the index position of the other items by one and increases the length of the new array. Multiple values can be added to the array passing comma-separated items as function parameters.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" target="_blank" rel="noopener">splice()</a>

Changes the contents of an array by removing existing elements and/or adding new elements.

The splice() method is very useful method as it can add and/or remove one or more items from an array. If number of added items do not match with the removed items in an array then  the final array will have different length.

Basic Syntax: Following is the basic syntax of splice() method.

// basic splice() syntax
arr.splice(index[, deleteCount, elem1, ..., elemN])
splice(1, 0, "new");

The splice() method starts from the position index (with origin 0): removes deleteCount elements and then inserts elem1, ..., elemN at their place. Returns the array of removed elements. The splice(1, 0, "new") method (line 3) removes 0 items from index 0 and inserts "new" item.

Revisiting cars array, which has four values, lets use splice() to add, remove or add & remove items from its array.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

// inserting an item with splice
cars.splice(1, 0, "Lexus"); 
//access cars
cars;//OUTPUT => (5) ["Toyota", "Lexus", "Ford", "Honda", "GM"]

// remove one item from index 3
cars.splice(3, 1); //OUTPUT => (1) ["Honda"]
//access cars Array
cars; //OUTPUT => (4) ["Toyota", "Lexus", "Ford", "GM"]

In the example above, one item "Lexus" was inserted at index 1 and zero item was removed (line 8). The modified cars array shows it has 5 arrays with "Lexus" at index 1 (line 9). Now lets remove one item from index 3 (line 13) and the removed item was "Honda" (line 13) and cars array has 4 items (line 15)

Using cars array with five items from line 10 (above), lets remove and insert items from its array.

//cars array with five items 
let cars = ["Toyota", "Lexus", "Ford", "Honda", "GM"];

// remove two items at index 2 replace one
cars.splice(2, 2, "BMW"); //OUTPUT => (2) ["Ford", "Honda"]
//access cars array
cars; //OUTPUT => (4) ["Toyota", "Lexus", "BMW", "GM"]

//remove items after index 2
let remove = cars.splice(2);
//call remove array
remove;// OUTPUT => (2) ["BMW", "GM"]
//access cars array
cars; //OUTPUT => (2) ["Toyota", "Lexus"]

In the example above, the cars array has five items (line 17). Using splice() two items were removed starting at index 2 and replaced with one item "BMW" at index 2 (line 20). After the splicing() action, the cars array has only 4 items: Toyota, Lexus, BMW, GM.

Lets use splice() method to remove all items after a defined index position. Using the cars array from line 22,  items after index 2 were removed and the results were assigned to remove variable as an array (line 25) and remove array out showed that two items (BMW, GM) were removed from index 3-4. The final cars array has two items Toyota and Lexus at index 0 and 1.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse" target="_blank" rel="noopener">reverse()</a>

Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.

In our cars array we will use reverse() method to reverse the order of the items. The reverse() method does not take parameters.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

// reverse items orders
cars.reverse(); //OUTPUT => (4) ["GM", "Honda", "Ford", "Toyota"]

In the example above, "Toyota" is at index 0 and "GM" at index 3 position (line 2). After reverse() method (line 5) execution the positions of the items was reversed, "GM" at index 0 and "Toyota" at index 3 in the cars array.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill" target="_blank" rel="noopener">fill()</a>

Fills all the elements of an array from a start index to an end index with a static value.

Revisiting Cars array example there are four items, with fill() method all the items will be replaced by the value passed as function parameter.

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

//replaces all items
cars.fill("Lexus"); // OUTPUT => (4) ["Lexus", "Lexus", "Lexus", "Lexus"]

In line 5, when cars.fill("Lexus") was applied all the for values of the cars array were replaced with the same "Lexus" value.

The fill() method takes optional arguments as the start and end of index position as shown in the example below:

//cars array from line 2(above)
let cars = [ "Toyota", "Ford", "Honda", "GM" ];

//fill selected items
cars.fill("Lexus", 1); // OUTPUT => ["Toyota", "Lexus", "Lexus", "Lexus"]
cars.fill("Lexus", 1, 3); // OUTPUT => ["Toyota", "Lexus", "Lexus", "GM"]

In line 10, when parameters to fill ("Lexus") and start position 1 were supplied without end position, all items starting index 1 were filled with supplied fill value ("Lexus"). When end value was added (line 11) only items starting at index 1 and ending at index 3 were filled. Additional examples are available in the MDN Documentation.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" target="_blank" rel="noopener"><strong>sort()</strong></a>:

Sorts the elements of an array in place and returns the array.

Array sort() method sorts array items as "string" by default. All elements, irrespective of integer or strings, they are converted to strings and compared in lexicographic (alphabetical) order (for example, 2 being greater that 15).

//initialize cars array with four items 
let cars = [ "Toyota", "Ford", "Honda", "GM" ];
// default sort()
cars.sort(); //OUTPUT => ["Ford", "GM", "Honda", "Toyota"]

//lcars array with lowercase items 
let lcars = [ "toyota", "ford", "honda", "gm" ];
//sort() lowercase string
lcars.sort(); //OUTPUT => ["ford", "gm", "honda", "toyota"]

By default, sort() method applies sorting alphabetically that are either uppercase (line 4) or lowercase (line 9).

// re-initialize cars array (Honda starts with lowercase)
let cars = [ "Toyota", "Ford", "honda", "GM" ]; 

//sort mixed first letter
cars.sort();// OUTPUT => (4) ["Ford", "GM", "Toyota", "honda"]

In the example above, when array string items are mixed ("honda" starts with lowercase), items with uppercase come before the lowercase item (line 14).

// Initialize cars array to include number
let myCar = ["Toyota", "Corolla", 2018, "2 Engine"];

//sorting with number & strings
myCar.sort(); //OUTPUT => (4) ["2 Engine", 2018, "Corolla", "Toyota"]

In the example above myCar array is modified to include strings and number and sort() output shows that number comes before upper and lowercases (line 19)

Sorting of Numbers
The JS sort() method by default sorts values as strings. Sorting string values such as Toyota, Honda, Lexus in alphabetical order (Honda comes before Lexus) makes sense. However, when numbers are sorted as strings then “20” comes before “100” which returns incorrect results and practically its not helpful.

//initialize myNum array
let myNum = [ 1, 2, 15, 40, 8, 100 ];
//default sort()
myNum.sort();//OUTPUT => [1, 100, 15, 2, 40, 8]

In the example above, 100 comes before 15 or 2 because the stings are order in lexicographic (alphabetic) order where 1 < 2 and 100 < 15 which does not make much sense. This type of numeric sorting problem could be fixed by using a compare function.

The Compare Function
The following function compares two numerical values , it sends the values to the compare function and sorts the values in ascending order (except NaN & infinity).

//basic syntax (ascending/descending order)
function name(a, b) {
  return a - b; // ascending order
 // return b - a;  // descending order
}

In the above syntax the compare function subtract b from a for ascending order (line 3). Similarly, if a is subtracted from b, the compare function  perform sort in descending order.

//initialize myNum array
let myNum = [ 1, 2, 15, 40, 8, 100 ];

//sort ascending
myNum.sort(function name(a, b) {
     return a - b; // ascending order
});
//access myNum
myNum; //OUTPUT => [1, 2, 8, 15, 40, 100]

//sort descending order
myNum.sort(function name(a, b) {
     return b - a; // descending
});
//access myNum
myNum; //OUTPUT =>[100, 40, 15, 8, 2, 1]

In the example above, myNum array is initialized with six numerical items in the array (line 2). To sort the values of myNum array in ascending order the compare function created previously has to passed as argument to sort() function. When applied as shown (line 4-7), the myNum array values were sorted by size or in ascending order (line 9). An example to sort in descending number is shown in lines 11-15.

Alternately, a comparison function can be created first and the function is passed as argument to sort numerical values of an array variable. A re-write of above ascending order sort() function (line 4-7) as a comparison arrow function is shown below:

//initialize myNum array
let myNum = [ 1, 2, 15, 40, 8, 100 ];

//initialize sort number (ascending)
const numAscend = (a, b) => {
     return a - b;
}
//sort myNum
myNum.sort(numAscend); //OUTPUT => [1, 2, 8, 15, 40, 100]

A comparison arrow function to sort numbers by size (ascending order) was initialized and assigned to numAscend const (lines 5-7). When the numAscend function was passed as argument of myNum.sort(), we got the same output (line 9). This method is much shorter and easy to read as well.

Additional use case examples of array.sort() are available in the MDN Documentation.

Accessor Methods

Unlike the mutator methods, the accessor methods do not modify the original elements of an array but return a copy or representation instance. In this section, we will examine some of these methods to concatenate arrays, convert arrays to strings, copy portions of an array to a new array and find the indices of arrays.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" target="_blank" rel="noopener">concat()</a> :

Returns a new array comprised of this array joined with other array(s) and/or value(s).

The concat() method merges two or more arrays together into a new array. It accepts any number of arguments – either arrays or values (line 2).

//basic concat syntax
arr.concat(arg1, arg2...)

// initialize cars, models & year arrays
let cars = [ "Toyota", "Honda", "Ford"];
let models = [ "Camry", "Civic", "Fusion" ];
let year = [2018];

// concatinate into myCars array (2 arrays)
let myCars = cars.concat(models);
//access myCars array
myCars;//OUTPUT =>(6) ["Toyota", "Honda", "Ford", "Camry", "Civic", "Fusion"]

//concat 3 arrays into myNewCars
let myNewCars = cars.concat(models, year);
//access myNewCars array
myNewCars; 
//OUTPUT
(7) ["Toyota", "Honda", "Ford", "Camry", "Civic", "Fusion", 2018]

In the example above, three arrays cars, models and year are initialized (Lines 5-7). In line 10, myCar array is concatenated with models array and the merged array is assigned to myCars array. The new myCar array outputs combination of two arrays. Similarly, in line 15, two arrays models and year are merged with cars array and assigned the output to myNewCars array (lines 15). The myNewCars array merges all three arrays into one single array. Using concat() method, multiple arrays can be merged into a single new array.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join" target="_blank" rel="noopener">join()</a> :

Joins all elements of an array into a string and returns a new string.

The join() method joins one or more arrays into a new string. The elements are separated, by default, by a comma ( , )  without any character between them.

// basic syntax
arr.join([separator])

// initialize cars array
let cars = [ "Toyota", "Honda", "Ford"];

//join the items into a string
let carString = cars.join();
//access carString array
carString; // OUTPUT => "Toyota,Honda,Ford"

In the example above, cars array items were join with join() method without any arguments (default), and values were assigned to a new carString array (line 8) and its output was comma-separated string (line 10).

//join array items into a string with parameter 
let carString = cars.join(', ');
let carString1 = cars.join(' + ');
let carString2 = cars.join('');

//access carString, carString1 & carString2
carString; // OUTPUT => "Toyota, Honda, Ford"
carString1; // OUTPUT => "Toyota + Honda + Ford"
carString2; // OUTPUT => "ToyotaHondaFord"

In the example above, using the same cars array (line 5) the elements were joined with comma and a space (line 12), then plus and a space (line 13) and with a empty string (line 14). With added parameters (lines 17-18) the joined elements can be formatted into more readable string. An empty string argument eliminates comma completely (line 19).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" target="_blank" rel="noopener">slice()</a> :

The slice() method returns copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified..

The slice() method syntax begins with zero-based index at which to begin extraction. If unspecified slice begins from index 0. For the end point of slice extraction it extracts up to but NOT including end.

// basic syntax
arr.slice([begin[, end]])

//initialize cars array with four items
let cars = [ "Toyota", "Ford", "Honda", "GM", "BMW" ];

// slice cars array 2 to 5
let myCars = cars.slice(2, 4);
// access myCars;
myCars; // OUTPUT => (2) ["Honda", "GM"]

//slice a new array from 2 to end of Array
let myCars = cars.slice(2);
//access myCars new Array
myCars; //OUTPUT => (3) ["Honda", "GM", "BMW"]

In the example above, slice() creates a new array myCars from cars (line 8) from the elements beginning at index 2 through the fifth element but not including 5 (indexing from 2 to 4) as shown in myCars output (line 10). If end to extract is omitted (line 13) slice extracts through the end of array (line 15) indexing three elements beginning at index 2.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" target="_blank" rel="noopener">indexOf()</a> :

Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

The indexOf() method is used to locate the value of selected element(s) in an array. It compares searchElement to elements of the array using strict equality (the same method used by the === or triple-equals operator). The fromIndex in the syntax refers to the index to start the search at (default is 0 & entire array is searched).

// basic syntax
arr.indexOf(searchElement[, fromIndex])

//initialize cars array with four items
let cars = [ "Toyota", "Ford", "Honda", "GM", "BMW" ];

//find 2 index of an array item
cars.indexOf("Honda"); //OUTPUT => 2

//indexing non-existing item
cars.indexOf("Lexus"); //OUTPUT => -1

In the example above, indexOf() method is used to search the index value in Cars array (line 5). Using indexOf() in cars array index value of Honda was determined as 2 (line 8). If an non-existing item  (eg. Lexus) is searched, index value of -1 (refers not found) is returned (line 11).

One of the drawbacks of the indexOf() method is that value of NaN can’t be found with index of in an array.

To quote from 2alityIt’s a well-known limitation of Array.prototype.indexOf() that it can’t find NaN, because it searches for elements via === [1]. Below we will look few examples to overcome this problem.

//initialize carsN array with NaN element
let carsN = ["Toyota", "Ford", NaN, "GM"];

//access with indexOf
carsN.indexOf(NaN); //OUTPUT => -1
// access using includes()
carsN.includes(NaN); //OUTPUT => true

In the example above, the indexOf() method, a value of -1 is returned (line 5) which refers to – not found. But this is wrong value because NaN is index at 2 (line 2) as === equality doesn’t work for NaN.  Array includes() method, check inclusion of element in array (line 7) but only returns true ( if found) and false (if not found).

In 2ality blog post, Dr. Axel Rauschmayer suggest creating a general elemIs() function to overcome this problem as shown below:

//initialize carsN array with NaN element
let carsN = ["Toyota", "Ford", NaN, "GM"];

//initialize a general function
function elemIs(x) {
  return Object.is.bind(null, x);
}
//access using elemIs() function
carsN.findIndex(elemIs(NaN));//OUTPUT => 2

In the example above, a simple function elemIs() was created (lines 5-7). Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" target="_blank" rel="noopener">array.findIndex()</a> method with elemIs() function as its parameter, position of NaN element can be correctly located (line 16).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf" target="_blank" rel="noopener">lastIndexOf()</a> :

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. The array is searched backwards, starting at fromIndex.

Basic syntax of the lastIndexOf() method is shown below (line 2) where searchElement refers to element to locate in the array, and fromIndex is optional.

Just like in indexOf() method, the lastIndexOf compares searchElement to elements of the array using strict equality (the same method used by the ===, or triple-equals, operator).

// basic syntax
arr.lastIndexOf(searchElement, fromIndex)

//initialize cars array with four items
let cars = [ "Toyota", "BMW", "Honda", "GM", "BMW" ];

// find last instance of an array item
cars.lastIndexOf("BMW"); //OUTPUT => 4

In the example above,  when the lastIndexOf() method was applied (line 8) to check whether "BMW" was the last index of cars array (line 5) and its output showed that it was indeed the last index (i.e. 4).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString" target="_blank" rel="noopener">toString()</a> :

Returns a string representing the array and its elements.

The toString() method converts an array into comma-separated array values.

/initialize cars array with four items
let myCar = [ "Toyota", "Camry", 2018 ];

// convert array to string
myCar.toString(); //OUTPUT => "Toyota,Camry,2018"

Iteration Methods

The Iteration method make use of JS loop & iteration and operate on every item in an array, once at a time. These methods allow to perform actions such as filtering out the desired results of an array, reduce array items down to a single value, and search through arrays to find values or indices.

Arrow Function – Revisit

To quote the MDN Documentation: An arrow function expression has a shorter syntax than a function expression and does not have its own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a>, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors. They are written as equals sign ( = ) followed by a greater than ( > ) sign : => .

//function syntax
let functionName = function() {
  // code block
}
//invoke function
functionName();

//arrow function syntax
let functionName = () => {
// code block
}
// function with one parameter
let functionName = parameter1 => {
  //code blocks
}
//invoke function
functionName();

A JS function can be defined as a block of reusable (procedure) codes that can be executed to perform a task or calculate value. A typical function syntax and invoking a function is shown above (lines 2-6).

The arrow function is represented with much shorter syntax and written as shown above (line 8-17). Parameters can be included in the parentheses in function (line 2-6) and arrow function (line 9). In arrow function, the parentheses (line 9) can be ommited if there is only one parameter (line 13).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" target="_blank" rel="noopener">forEach()</a> :

The <strong>forEach()</strong> method executes a provided function once for each array element.

A basic syntax of forEach() method is shown below (lines 2-4).

// basic syntax
arr.forEach(function(item, index, array) {
  // ... do something with item
});

//initialize cars array
let cars = ["Toyota", "Ford", "Honda", "GM"]; //

// Print out each item in the array
cars.forEach(Car => { //from cars to individual car
    console.log(Car);
})
//OUTPUT
Toyota
Ford
Honda
GM

In the example above, cars array is initialize with four car names (line 7). Using forEach() method (lines 10-12), each item in the cars array can be as shown in the output (lines 14-17).

An alternative method to achieve the same results is by using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for" target="_blank" rel="noopener">for</a> loop keyword. In this method for keyword loops through the length property of the array  as shown below (lines 19-21).

// Loop through the length of the array
for (let i = 0; i < car.length; i++) {
    console.log(car[i]);
}
//OUTPUT
Toyota
Ford
Honda
GM

In the case of an array, forEach() is more concise and simpler iteration method.

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" target="_blank" rel="noopener">map()</a> :

Creates a new array with the results of calling a provided function on every element in this array.

The array.map() method transforms one array into a new array after performing some operation on each item of the array. The original array is not modified and the function returns a new array value. The map() method must be assigned to a new variable.

Lets revisit cars array and use map() to print each item, add extra character to each items and determine the length of character of each items in the array.

// basic syntax
let mapName = arr.map(function(item, index, array) {
  // returns the new value instead of item
})

//initialize cars array
let cars = ["Toyota", "Ford", "Honda", "GM"];

// Print out each item in the array
let printCars = cars.map(car => { // individual car
    console.log(car);
});
//OUTPUT
Toyota
Ford
Honda
GM

In the example above, map() method iterates each item in cars array (line 7) and returns each iteration of the loop to the console (lines 14-17) one at a time until all the elements are printed. The map() method is assigned to the printCars variable.

//add extra character X in cars array
let carX = cars.map(car => {
    return `${car}X`;
});
//access carX array
carX; //OUTPUT => ["ToyotaX", "FordX", "HondaX", "GMX"]

//counting length of each element
let cars = ["Toyota", "Ford", "Honda", "GM"];
//map element length
let carLength = cars.map(item => item.length)
console.log(carLength);// OUTPUT => 6, 5, 4, 2

In the example above, map() is used to add an extra character (X) to each elements in the cars array (lines 19-21) and carX outputs all the elements with extra X  (lines 23). Similarly, using map() method and array.length property, length of each elements of the cars array (line 26) could be counted and output list was assigned to carLength array (lines 28-29).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="noopener">filter()</a> :

Creates a new array with all of the elements of this array for which the provided filtering function returns true.

The array.filter() method calls a filtering function once for each elements in an array and returns all the elements that match the condition into a new array. If no elements in the array pass the criteria then an empty array will be return. The filter() method does not mutate (change) the original array.

The basic syntax array.filter() method shown below (line 2-4).

// basic syntax
let newArray = arr.filter(function(item, index, array) {
  // should return true if the item passes the filter
});

//initialize cars array
let cars = ["Toyota", "Ford", "Honda", "Hyundai", "BMW"];

// filter cars that start with "H" into a new list
let newCars = cars.filter(car => {
  return car[0] === "H";
});
//access newCars
newCars; // OUTPUT => ["Honda", "Hyundai"]

In the example above, array.filter() method is applied to search each elements of cars array (line 7) and filter out the list of elements with "H" at the index 0 and assign the list to newCars (lines 10-12).  The newCars, outputs two elements "Honda" and "Hyundai" that start with "H" (line 14).

Method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" target="_blank" rel="noopener">reduce()</a> :

The <strong>reduce()</strong> method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

The array.reduce() method performs the callback function once for each elements in the array returns a single value. Its basic syntax is shown below (lines 2-4). The callback function parameters include:

  • reducer : the single returned value by the reduce() call back function
  • acc : it accumulates callback’s return value
  • curVal : the current element being processed
  • curIndex : The index position of the current element being processed (optional)
  • arr : the array being processed (optional)
  • initValue : Initial value for the first call (optional)

The array.array() method is little intricate and explained in more detail in other learning-note post Learning JavaScript Array.Reduce() Method.

//basic syntax
let reducer = arr.reduce(function(acc, curVal, curIndex, arr) {
  // ...
}, initValue);

//initialize numbers array
let numbers = [ 9, 56, 29, 11, 41, 18 ]; 

// total of all numerical values
let total = numbers.reduce((a, b) => {
    return a + b;
});
//access total
total; // OUTPUT => 164

//initialize cars array
let cars = ["Toyota", "Ford", "Honda", "Hyundai", "BMW"];
// total of all numerical values
let reduceCars = cars.reduce((a, b) => {
    return a + b;
});
//access reduceCars
redudeCars; // OUTPUT => "ToyotaFordHondaHyundaiBMW"

In the example above, numbers array is assigned with six number as array elements (line 2). The array.reduce() can be used to find the sum of all the elements in an array. Using reduce() method each elements of numbers array within the loop are added and assigned to a total variable (lines 5-7).  The total outputs 164 which is sum of all the elements in numbers array.

Likewise, array.reduce() can also be used to other data types, number, string, array etc. An example of reducing all cars array elements into a single string value is shown above (lines 11-19).

Note: The array.reduceRight() method is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" target="_blank" rel="noopener">array.reduce()</a> method that performs starting from right-to-left.

Methods <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" target="_blank" rel="noopener">find()</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" target="_blank" rel="noopener">findIndex()</a> :

The array.find() method returns the value of the first element found in the array, if an element in the array satisfies the provided testing function or undefined if not found. On the other hand, the findIndex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.

Both the array.find() and array.findIndex() methods execute the function once for each element present in the array and return the value (in case find method) and index value (in case of findIndex method) of the first element in an array that pass the test. Both methods do not check the remaining values. They also do not execute the function on empty elements and do not change the original array.

//initialize carModels array
let carModels = ["Camry", "Corolla", "Prius", "Tundra", "Tacoma"];

// Check if a given value is a truck
const isTruck = truck => {
    return [ "Trunda", "Tacoma" ].includes(truck);
}
// using arrow function
let isTruck = truck => truck === "Tundra"; // an array item
//Invoke find() 
carModels.find(isTruck); //OUTPUT => Tundra

// Check if a given value is in the array
let isChevy = truck => truck === "Silvarado"; // NOT an array item
//Invoke find() 
carModels.find(isChevy); //OUTPUT => undefined

In the example above, carModels array is initialized with five elements (three sedans and two trucks) (line 2).  Using a simple arrow function isTruck (line 9) to check if a value equals to "Tundra" (line 9) and istruck as array.find() function parameter (line 11), we can check whether it matches with each elements in carModels array. And if any element value is equal to "Tundra" its value is returned (line 11). If value is not matched it returns "undefined) (line 16) because there is "Silvarado" in not in carModels array (line 2).

//Invoke findIndex() of a listed element
carModels.findIndex(isTruck); //OUTPUT => 3
//Invoke findIndex() of NOT listed element
carModels.findIndex(isChevy); //OUTPUT => -1

Using the same example from above, when isTruck (line 9) is used with findIndex() function, it returns 3 instead of Tundra (line 18). Likewise, when not listed element value "Silavardo" is passed using isChevy as findIndex() function (line 14), it returns -1 and not undefined.

Note: The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" target="_blank" rel="noopener">array.find()</a> method is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" target="_blank" rel="noopener">array.findIndex()</a> method which returns index value instead of the element itself.

Methods <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every" target="_blank" rel="noopener">every()</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" target="_blank" rel="noopener">some()</a> :

The array.every() method returns true if every element in this array satisfies the provided testing function. On the other hand, the array.some() method returns true if at least one element in this array satisfies the provided testing function..

The method the array.every() method executes function once for each element in an array and returns true only when all elements pass the condition, otherwise returns false. Both the every() & some() methods do not immutate original array and do not execute on elements without any value.

// initialize year array
let year = [2015, 2016, 2017, 2018];

//assign carYear to check an array item
let carYear1 = year.every(car => car >= 2015);//OUTPUT => true
//check item not listed in array
let carYear2 = year.every(car => car >= 2016);//OUTPUT => false

In the example above, using every() method we check if values in the year array (line 2) that our cars were built in 2015 or later (line 5). carYear1 function pass the condition (line 5) because all the cars were built later than 2015 and this returns true. However,  in the case of carYear2 function returns false because there is one item listed 2015 fails the test though rest of the cars were built either 2016 and later.

Similar to the every() method, the array.some() method also executes function once for each element in the array but returns true even if only one element pass the test. It returns false only when none of the element in the array pass the test.

//check with some() if any item 
let carYear1 = year.some(car => car > 2015); //OUTPUT => true
//check with some non-compliant item
let carYear2 = year.some(car => car < 2015); //OUTPUT => false

In the example above, using some() method we checked whether some values in the year array (line 2) are greater than 2015 and it passes the test on first item and returns true (line 9). But when it was  checked whether any values were smaller than 2016 and yes there was one with 2015 but still it fails the test (there are values greater than 2016) and returns false (line 11).

Methods <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values" target="_blank" rel="noopener">values()</a> & keys() :

The array.values() returns a new Array Iterator object that contains the values for each index in the array. On the other hand, the array.keys() method returns a new Array Iterator that contains the keys for each index in the array.

The basic syntax of array.values() method is shown below (line 2) and it returns a new array iterator object.

// basic syntax
arr.values();

//initialize carsA array
const carsA = ["Toyota", "Ford", "Honda", "GM"];
const carsB = carsA.values();

// value iteration loop
for (const value of carB) {
  console.log(value); 
}
//OUTPUT
Toyota
Ford
Honda
GM

In the above example(adopted from the MDN documents), carsA array is initialized with four elements (car names) (line 5). Using array.values() method carsA array elements were assigned to a new carsB array (line 6). Using a for loop, the values of each elements of carsB array (lines 9-11) can be printed in the browser console (lines 13-16).

The basic syntax of array.keys() method is similar to array.values() discussed above (line 2) which also returns a new array iterator object.

// basic syntax
array.keys();

//initialize carsA array
const carsA = ["Toyota", "Ford", "Honda", "GM"];
const carsB = carsA.keys();

//key iteration loop
for (let key of carsB) {
  console.log(key); 
}
//OUTPUT
0
1
2
3

The example above is the same carsA array used in array.values() method. The array.keys() method operatates similarly (lines 9-11) except it returns iterator array that contains keys of each array (lines 13-16).

Tip: There are other methods and use cases listed in MDN Documents including creating multi-dimensional array, tabulation of array values and additional use cases of methods discussed in this post.

Wrapping Up

In this post, we looked at built-in mutator, accessor and iteration methods to modify JS arrays. Using simple code snippets we modified original array elements with mutator methods, and created new array representation using accessor methods to perform concatenation, convert arrays to strings, copy portions of an array to a new array etc. Finally we explored iteration method to filtering out desired elements from original array and reducing an array to single value.

Related Post : Learning JavaScript Array.Reduce() Method

Useful Resources & Links

While preparing this post, I have referred the following references extensively. Visit original link for additional information.