The Most Important Array Methods in JavaScript Explained

The Most Important Array Methods in JavaScript Explained

Are you a JavaScript developer? Then you should be familiar with the most commonly used ES5 and ES6+ array methods.

Arrays in JavaScript are like objects whose prototypes have methods to perform some sort of operation on them. In this article, we will review some of the most important array methods in JavaScript, and how we can use them. For these examples we will be working with arrow functions.

Array.filter Method

The syntax for the Array.filter method is as follows:

filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )

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

Array.filter() calls a provided arrow function once for each element in an array, and constructs a new array of all the values for which arrow function returns a value that coerces to true. Arrow function is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the arrow function test are skipped, and are not included in the new array.

const users = [
{name: 'Michael Scott', age: 38}, 
{name: 'Stanley Hudson', age: 41}, 
{name: 'Dwight Schrute', age: 25}, 
{name: 'Pam Beesly', age: 32},
];

const result = users.filter(user => user.age > 30);

console.log(result);

 // [ { name: 'Michael Scott', age: 38 }, { name: 'Stanley Hudson', age: 41 }, { name: 'Pam Beesly', age: 32 } ]

Array.find Method

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

The syntax for the Array.find method is as follows:

find((element) => { ... } )
find((element, index) => { ... } )
find((element, index, array) => { ... } )

The find method executes the arrow function once for each index of the array until the arrow function returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.

const users = [
{name: 'Michael Scott', age: 38}, 
{name: 'Stanley Hudson', age: 41}, 
{name: 'Dwight Schrute', age: 25}, 
{name: 'Pam Beesly', age: 32},
];

const result = users.find(user => user.age > 30);

console.log(result)

//  { name: 'Michael Scott', age: 38 }

As you can see, Array.find() returns the first value that it finds that satisfies the condition. So if you need to return just one result, you may want to use find().

Array.findIndex Method

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

The syntax for the Array.find method is as follows:

findIndex((element) => { ... } )
findIndex((element, index) => { ... } )
findIndex((element, index, array) => { ... } )

The findIndex() method executes the arrow function once for every index in the array until it finds the one where arrow function returns a truthy value.

If such an element is found, findIndex() immediately returns the element's index. If arrow function never returns a truthy value (or the array's length is 0), findIndex() returns -1.

const users = [
{name: 'Michael Scott', age: 38}, 
{name: 'Stanley Hudson', age: 41}, 
{name: 'Dwight Schrute', age: 25}, 
{name: 'Pam Beesly', age: 32},
];

const result = users.findIndex(user => user.age < 30);

console.log(result)

// 2

Here our output is 2 which would be the object containing the name Dwight Schrute in the above example. Note that the index starts with zero.

Array.forEach Method

The forEach() method executes a provided function once for each array element.

The syntax for the Array.forEach method is as follows:

forEach((element) => { ... } )
forEach((element, index) => { ... } )
forEach((element, index, array) => { ... } )

Array.forEach() calls a provided arrow function once for each element in an array in ascending index order. It is not invoked for index properties that have been deleted or are uninitialized.

const users = [
{name: 'Michael Scott', age: 38}, 
{name: 'Stanley Hudson', age: 41}, 
{name: 'Dwight Schrute', age: 25}, 
{name: 'Pam Beesly', age: 32},
];

users.forEach(user => console.log(user))

// { name: 'Michael Scott', age: 38 },  { name: 'Stanley Hudson', age: 41 },  { name: 'Dwight Schrute', age: 25 }, { name: 'Pam Beesly', age: 32 }

Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Array.map Method

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

The syntax for the Array.map method is as follows:

map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })

Array.map calls a provided arrow function once for each element in an array, in order, and constructs a new array from the results. arrow function is invoked only for indexes of the array which have assigned values (including undefined).

It is not called for missing elements of the array; that is:

  • indexes that have never been set;

  • indexes which have been deleted.

const numbers = [10, 20, 30, 40, 50];

const multiplied = numbers.map(number => number * 2);

console.log(multiplied);

//  [ 20, 40, 60, 80, 100 ]

In the above code, inside the arrow function, we are multiplying each number by 2 and returning it.

When not to use map()

Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use forEach or for...of instead.

You shouldn't be using map if:

  • you're not using the array it returns; and/or

  • you're not returning a value from the callback.

Array.some Method

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

The syntax for the Array.some method is as follows:

some((element) => { ... } )
some((element, index) => { ... } )
some((element, index, array) => { ... } )

The some() method executes the arrow function once for each element present in the array until it finds the one where arrow function returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. Arrow function is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values.

some() does not mutate the array on which it is called.

const grades = [80, 52, 92, 62, 75];

const passed = grades.some(grade => grade > 65);

console.log(passed);

// true

In the above example, the output we get is true because there was at least one element in the array that passed the condition which happened to be the first element in the array.

Array.every Method

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

The syntax for the Array.every method is as follows:

every((element) => { ... } )
every((element, index) => { ... } )
every((element, index, array) => { ... } )

The every method executes the provided arrow function once for each element present in the array until it finds the one where the arrow function returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if the arrow function returns a truthy value for all elements, every returns true.

const grades = [80, 52, 92, 62, 75];

const passed = grades.every(grade => grade > 65);

console.log(passed);

// false

As you can see, we are using the same example as we did for Array.some(). The only difference now is that we get false as the output. This is because the condition needs to be satisfied by every element in the array. Since only some elements satisfy the condition, we get false.

Array.includes Method

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

The syntax for the Array.includes method is as follows:

includes(searchElement)
includes(searchElement, fromIndex)
const users = ['john', 'mary', 'sam', 'leo', 'arnold'];

const userExists = users.includes('leo');

console.log(userExists);

// true

In the above example we get back true because the string 'leo' is included in the users array.

Array.reduce Method

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The syntax for the Array.reduce method is as follows:

reduce((previousValue, currentValue) => { ... } )
reduce((previousValue, currentValue, currentIndex) => { ... } )
reduce((previousValue, currentValue, currentIndex, array) => { ... } )
reduce((previousValue, currentValue, currentIndex, array) => { ... }, initialValue)

The arrow function should be one that takes four arguments. reduce calls the callback, as a function, once for each element after the first element present in the array, in ascending order.

The Function is called with four arguments:

  • the previousValue (value from the previous call to callbackfn)

  • the currentValue (value of the current element)

  • the currentIndex, and

  • the object being traversed

const numbers = [10, 20, 30, 40, 50];

const sum = numbers.reduce((accumulator, current) => {
    return accumulator + current;
});

console.log(sum);

// 150

In the above example, we use reduce() to calculate the sum of all elements in an array.

Conclusion

I hope you found these array methods as useful as I did when I first discovered them. I know there may be other methods that are as equally important but these are just the ones I know are very frequently used now to work with arrays. If you want to list more methods in the comments, I would love to read them. Thank you!