This article was published on July 2, 2020

15 useful methods to get the most out of JavaScript arrays


15 useful methods to get the most out of JavaScript arrays

Arrays are wonderful and a very particular type in JavaScript. There are many useful built-in properties and methods that will help you resolve any task which involves this kind of type. Today, we’re going to discuss 15 array methods every developer should know. So, let’s get started:

  • some()
  • every()
  • reduce()
  • map()
  • flat()
  • filter()
  • forEach()
  • findIndex()
  • find()
  • sort()
  • concat()
  • fill()
  • includes()
  • reverse()
  • flatMap()

This list is not enumerated as I don’t believe one method is more important than the other. Each method will resolve a different problem, so it’s important we’re familiar with all of them.

[Read: Python is great, but stop using it for every damn project]

some()

The some() tests whether at least one element in the array passes the test implemented by the callback function. The callback function will receive three arguments: the item, the index, and the full array. Additionally, it’s possible to assign a value for this when executing the callback by using the argument thisArg.

The <3 of EU tech

The latest rumblings from the EU tech scene, a story from our wise ol' founder Boris, and some questionable AI art. It's free, every week, in your inbox. Sign up now!

Definition:

Examples:

every()

The every() method is, in a way, similar to the some() method, but it tests whether all the elements in the array pass the test implemented by the callback function.

Definition:

Examples:

reduce()

The reduce() method executes a callback function once for each assigned value present in the array, taking four arguments:

  1. accumulator
  2. currentValue
  3. currentIndex
  4. array

The first time the callback is called, accumulator and currentValue can be either the initialValue if provided, and the first value in the array if not.

Definition:

How does reduce() work?

Let’s see with an example of how reduce() works:

If we go step by step and put in a table all the parameters plus the resulting value of the callback, we would get the following:

const initialValue = 10And the final result would be 10. In our particular case, I did not provide an initial value. Let’s try that next:

With this new scenario, our table would like this:

The reduce() function is great and it has several uses like summing all the values of an array or in an object array, counting for particular items in the array, grouping objects, merging arrays contained in an array of objects, removing duplicates, etc. And the final resulting value is 20.

map()

The map() method creates a new array populated with the results of the callback function for each element in the array. Similar to the other methods, the callback function will receive three arguments: currentValue, index, and array. As is with the case of reduce(), the callback is only invoked for indexes of the array which have assigned values (including undefined).

Definition:

Always be careful when using map().Remember that on each call will create a new array. If you don’t actually need the array and you are simply trying to iterate, use forEach() or for-of instead.

Examples:

As we mentioned map() will create a new array, so the following is a consequence of that:

Even though each array contains the exact same elements, they are not the same reference and thus the numbers === numbers2 resolves to false.

flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. By default, it will flatten one level.

Definition:

Examples:

Note that if we want to flatten all levels recursively, we can pass Infinity as the argument of the function.

filter()

Together with map() I think this is one of my favorites. The filter() method creates a new array with all the elements that pass the test implemented by the callback function.

Definition:

Examples:

forEach()

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

Definition:

Example:

There are two important considerations when using forEach()

  • There is no way to stop or break a forEach() loop other than throwing an exception.
  • forEach() expects a synchronous callback, and it won’t wait for promises to be resolved.

Let’s see an example of the latter:

Even though we would have expected the variable sum to have accumulated all the values in the array and have a value of 14, the output was 0 as the forEach() statement ended without awaiting for the promises, and thus the console.log statement was executed before the variable sum was updated. So be very aware of this situation as it can lead to your code, producing unexpected results.

findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided callback function. Otherwise, it returns -1, indicating that no element passed the test. Unlike other methods, findIndex() will execute the callback function even for indexes with unassigned values.

Definition:

Example:

find()

The find() method is similar to the findIndex() method. However, it returns the value of the first element which satisfies the provided callback function as supposed to its index. If no element satisfies the callback, then undefined is returned.

Definition:

Example:

sort()

The sort() function is very common and simply allows us to sort the elements of an array in place and returning the sorting array. The default sort order is ascending. The complexity and performance of this method cannot be guaranteed, as it depends on the implementation.

Definition:

Examples:

Always remember that the sorting happens in place, so:

The sort function will modify the existing array, and return a reference to the same array, and thus the original array and the returned array will be the same.

concat()

The concat() method is used to merge two or more arrays into a new array.

Definition:

Examples:

fill()

The fill() method changes all the elements in an array to a static value, from a start index (default 0) to an end index (default array.length). The updates will happen in place and will return a reference to the same array.

Definition:

Examples:

includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false. Note that the method includes() is case-sensitive when comparing strings and characters.

Definition:

Examples:

reverse()

The reverse() method reverses an array in place. By reversing we mean that the function will transpose the elements of the array, the first element will become the last, and the last the first element. This operation will mutate the original array and return a reference to the same.

Definition:

Examples:

flatMap()

The flatMap() method applies a function to each element of the array and then flatten the result into an array. It combines flat() and map() in one function.

Definition:

Example:

Summary

JavaScript arrays come with some great methods that can simplify our development efforts. Knowing them can save us time and, in some cases, even boost the performance of our code. I hope that today you learned some new array methods, or refreshed old concepts that you can use for your next project.

This article was originally published on Live Code Stream by Juan Cruz Martinez, founder, and publisher of Live Code Stream. He is a Software Engineer with more than 10 years of experience in the field, working in a wide variety of projects, from open source solutions to enterprise applications. Happily married, with a kid, officially engaged to JavaScript, in a love relationship with Python, and pursuing the writer’s dream! You can read this original piece here.

Live Code Stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.

Get the TNW newsletter

Get the most important tech news in your inbox each week.

Also tagged with