JavaScript Array Methods. The JavaScript Array object is a global…
By: Kevin Peery
Tags: Array Methods, React, JavaScript, Arrays, Vanilla Javascript

The JavaScript array object is a global object that is used in the construction of arrays; which are high-level list-like objects. They are pure vanilla JavaScript concepts that are important to understand and are also relevant to React projects since React is simply JavaScript. Many React concepts center around working with arrays in an immutable context. Immutability means that after an object has been created, it can never change.

Methods are functions stored as object properties. Below are some of the various methods that can be used on the array prototype:

map():

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

var array1 = [1, 2, 5, 9]; // pass a function to map

const map1 = array1.map(x => x * 2); console.log(map1);

// expected output: Array [2, 4, 10, 18]

We are going through each element in the array and multiplying it by 2.

find():

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

var array1 = [6, 10, 8, 140, 55]; var found = array1.find(function(element) {

return element > 10;

}); console.log(found);

// expected output: 140

We are looking at each element in the array and returning the first element found that is greater than 10, which is the provided testing function. What about the element 55? We found the first element that met the criteria of the testing function, element (>) 10, and returned that value, 140. Once found, the testing function has been met and we stop searching.

findIndex():

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating no element passed the test.

var array1 = [6, 10, 8, 140, 55]; function isLargeNumber(element) {

return element > 13;

} console.log(array1.findIndex(isLargeNumber));

// expected output: 3

We are processing each element in the array until we satisfy the provided testing function. The first element in the array that is greater than 13 is 140, which is at the 3rd index position of the array. Remember that array index values begin with zero (0). Therefore, our output will be 3.

filter():

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var words = ['cat', 'dog', 'autos', 'thankful', 'gracious', 'hopeful']; const result = words.filter(word => word.length > 6); console.log(result);

// expected output: Array ["thankful", "gracious", "hopeful"]

In the example above, all of the words greater than 6 characters in length are returned. The strings ‘cat’, ‘dog’, and ‘autos’ were not returned because they are less than 6 characters and did not meet the test criteria of word.length > 6.

reduce():

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

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

In the first example which produced the output of 10 we are simply adding 1 + 2 + 3 + 4 = 10. There is no InitialValue given so we start with the first element in the array. In the second example, where the output produced is 15, we are specifying the optional InitialValue, so the first element inserted into the original array of [1, 2, 3, 4] is 5, adding 5 to the previous example.

concat():

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var array1 = ['a', 'b', 'c'];

var array2 = ['d', 'e', 'f']; console.log(array1.concat(array2));

// expected output: Array ["a", "b", "c", "d", "e", "f"]

This simply merges the two arrays into a single array.

slice():

The slice() method returns a shallow 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.

var animals = ['cat', 'dog', 'chicken', 'swan', 'giraffe']; console.log(animals.slice(2));

// expected output: Array ["chicken", "swan", "giraffe"] console.log(animals.slice(2, 4));

// expected output: Array ["chicken", "swan"] console.log(animals.slice(1, 5));

// expected output: Array ["dog", "chicken", "swan", "giraffe"]

Firstly, we are slicing beginning at the 2nd index. Our element at index 2 is ‘chicken’ so we return the array from ‘chicken’ through ‘giraffe’.

Secondly, we are starting at index 2 and ending at index 4. At the index 4 is the string element ‘giraffe’. Notice that the end is not included so we are only returning ‘chicken’ and ‘swan’ without the 4th element, ‘giraffe’.

In the last example above, we are beginning the slice at the first element, which is ‘dog’ and ending at index 5, which is beyond the length of our array of 4 indexes. Therefore, we cleared that 4th index element, ‘giraffe’, and include it in our output. Remember that the end is not included in the output. However, If end is greater than the length of the sequence, slice extracts through to the end of the sequence ( arr.length ). That is why our output includes ‘giraffe’ in the last case.

splice():

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');

// inserts at 1st index position

console.log(months);

// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June'] months.splice(4, 1, 'May');

// replaces 1 element at 4th index

console.log(months);

// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

In the example above, we start changing the array at the 1st index, which is specified in the first argument of the splice() method. January is at the 0-index. After January is the 1st index of the array. At that index, we place ‘Feb’. The 0 provided as the 2nd argument of splice() method means that we are deleting nothing from the array. In our case, we are simply inserting ‘Feb’ right in front of ‘March’ in the 1st index of the array and removing 0 array elements.

In the second example above, at the index of 4, we are deleting 1 old array element (‘June’) and replacing it with ‘May’.

Hopefully, these various array methods help solidify your understanding of pure vanilla JavaScript concepts and prove themselves to be useful in creating React apps.

Sources: