DEV Community

Cover image for 15 must-know JavaScript array methods in 2020
Ibrahima Ndaw
Ibrahima Ndaw

Posted on • Updated on • Originally published at ibrahima-ndaw.com

15 must-know JavaScript array methods in 2020

Originally posted on my blog

In JavaScript, an array is a special variable that is used to store different elements. It has some built-in properties and methods we can use to add, remove, iterate, or manipulate data following our needs. And knowing JavaScript array methods can lift your skills as a developer.

In this post, we're going to see 15 array methods that can help you manipulate your data properly.

Notice that mostly in this post, we'll simplify the function passed as parameter.

// Instead of using this way
myAwesomeArray.some(test => {
  if (test === "d") {
    return test
  }
})
// We'll use the shorter one
myAwesomeArray.some(test => test === "d")
Enter fullscreen mode Exit fullscreen mode

1. some()

This method tests the array with a function passed as a parameter. It will return true if at least one element matches the test and false for the opposite.

const myAwesomeArray = ["a", "b", "c", "d", "e"]

myAwesomeArray.some(test => test === "d")
//-------> Output : true
Enter fullscreen mode Exit fullscreen mode

2. reduce()

This method receives a function which has an accumulator and a value as an argument. It applies the function to the accumulator and each value in the array to return at the end just a single value.

const myAwesomeArray = [1, 2, 3, 4, 5]

myAwesomeArray.reduce((total, value) => total * value)
// 1 * 2 * 3 * 4 * 5
//-------> Output = 120
Enter fullscreen mode Exit fullscreen mode

3. every()

This method tests the array with a function passed as a parameter. It will return true if each element of the array match the test and false for the opposite.

const myAwesomeArray = ["a", "b", "c", "d", "e"]

myAwesomeArray.every(test => test === "d")
//-------> Output : false

const myAwesomeArray2 = ["a", "a", "a", "a", "a"]

myAwesomeArray2.every(test => test === "a")
//-------> Output : true
Enter fullscreen mode Exit fullscreen mode

4. map()

This method receives a function as a parameter. And return a new array that contains an image of each element of the array. It will always return the same amount of items.

const myAwesomeArray = [5, 4, 3, 2, 1]
myAwesomeArray.map(x => x * x)

//-------> Output : 25
//                  16
//                  9
//                  4
//                  1
Enter fullscreen mode Exit fullscreen mode

5. flat()

This method creates a new array that contains the elements holden on the sub-array and flat it into the new array. Notice that, this method will go only one level depth.

const myAwesomeArray = [[1, 2], [3, 4], 5]

myAwesomeArray.flat()
//-------> Output : [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

6. filter()

This method receives a function as a parameter. And return a new array that contains all the elements of the array for which the filtering function passed as argument returns true.

const myAwesomeArray = [
  { id: 1, name: "john" },
  { id: 2, name: "Ali" },
  { id: 3, name: "Mass" },
  { id: 4, name: "Mass" },
]

myAwesomeArray.filter(element => element.name === "Mass")
//-------> Output : 0:{id: 3, name: "Mass"},
//                  1:{id: 4, name: "Mass"}
Enter fullscreen mode Exit fullscreen mode

7. forEach()

This method applies a function to each element of the array.

const myAwesomeArray = [
  { id: 1, name: "john" },
  { id: 2, name: "Ali" },
  { id: 3, name: "Mass" },
]

myAwesomeArray.forEach(element => console.log(element.name))
//-------> Output : john
//                  Ali
//                  Mass
Enter fullscreen mode Exit fullscreen mode

8. findIndex()

This method receives a function as a parameter and will apply it to the array. It returns the index of an element found and which satisfies the test function passed as an argument or -1 if none satisfies it.

const myAwesomeArray = [
  { id: 1, name: "john" },
  { id: 2, name: "Ali" },
  { id: 3, name: "Mass" },
]

myAwesomeArray.findIndex(element => element.id === 3)
//-------> Output : 2

myAwesomeArray.findIndex(element => element.id === 7)
//-------> Output : -1
Enter fullscreen mode Exit fullscreen mode

9. find()

This method receives a function as an argument and will apply it to the array. It returns the value of an element found in the array and which satisfies the test function. Otherwise, it returns undefined.

const myAwesomeArray = [
  { id: 1, name: "john" },
  { id: 2, name: "Ali" },
  { id: 3, name: "Mass" },
]

myAwesomeArray.find(element => element.id === 3)
//-------> Output : {id: 3, name: "Mass"}

myAwesomeArray.find(element => element.id === 7)
//-------> Output : undefined
Enter fullscreen mode Exit fullscreen mode

10. sort()

This method receives a function as a parameter. It sorts the elements of an array and returns it.

const myAwesomeArray = [5, 4, 3, 2, 1]

// Sort from smallest to largest
myAwesomeArray.sort((a, b) => a - b)
//-------> Output : [1, 2, 3, 4, 5]

// Sort from largest to smallest
myAwesomeArray.sort((a, b) => b - a)
//-------> Output : [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

11. concat()

This method will merge two or more arrays/values by concatenating it. It returns a new array with the elements.

const myAwesomeArray = [1, 2, 3, 4, 5]
const myAwesomeArray2 = [10, 20, 30, 40, 50]
myAwesomeArray.concat(myAwesomeArray2)
//-------> Output : [1, 2, 3, 4, 5, 10, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

12. fill()

This method fills all the elements of a given array with the same value, from a start index (default 0) to an end index (default array.length).

const myAwesomeArray = [1, 2, 3, 4, 5]

// The first argument (0) is the value
// The second argument (1) is the starting index
// The third argument (3) is the ending index
myAwesomeArray.fill(0, 1, 3)
//-------> Output : [1, 0, 0, 4, 5]
Enter fullscreen mode Exit fullscreen mode

13. includes()

This method will return true if the array contains a certain element, and false if not.

const myAwesomeArray = [1, 2, 3, 4, 5]

myAwesomeArray.includes(3)
//-------> Output : true

myAwesomeArray.includes(8)
//-------> Output : false
Enter fullscreen mode Exit fullscreen mode

14. reverse()

This method reverses an array. The first element becomes the last, and the last element will be the first.

const myAwesomeArray = ["e", "d", "c", "b", "a"]

myAwesomeArray.reverse()
//-------> Output : ['a', 'b', 'c', 'd', 'e']
Enter fullscreen mode Exit fullscreen mode

15. flatMap()

The 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.

const myAwesomeArray = [[1], [2], [3], [4], [5]]

myAwesomeArray.flatMap(arr => arr * 10)
//-------> Output : [10, 20, 30, 40, 50]

// With .flat() and .map()
myAwesomeArray.flat().map(arr => arr * 10)
//-------> Output : [10, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

Latest comments (70)

Collapse
 
vitjaz profile image
Vitaliy • Edited

Why about "flat()" -> "Notice that, this method will go only one level depth."?

On MDN - "The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.".

Collapse
 
marcode_ely profile image
Marcos Aguilera Ely

Thanks a lot, this is one most important post for me, I don't shame it.

Collapse
 
aybee5 profile image
Ibrahim Abdullahi Aliyu

Awesome, namesake. I was discussing with a Senior today about HOF and I just see this.
However I'm confused, what's the difference between filter() and find()

Collapse
 
cherucole profile image
Cherucole

I enjoyed every bit of this, simple clear examples. Now depends on how we implement them

Collapse
 
costinmanda profile image
Costin Manda

Some note towards C# people who look at this and think it's the same as LINQ. It is not, as most of these methods create a new array as a result. Usually it doesn't matter as much, but consider what happens if the array is very large and you first map it to some complex and heavy calculation and only then you filter it. It may seem obvious, but only if you actually think about it, which to my shame I only did recently.

Also, shameless plus for my own library that uses ES6 iterators/generators to emulate LINQ in Javascript: siderite.dev/blog/linq-in-javascri... ;)

Collapse
 
marcossco profile image
Marcos dos Santos Carvalho

Thanks, your post is awesome.

Collapse
 
adammescher profile image
Adam Mescher • Edited

Greatly appreciate your effort for creating this list. It allowed me to get a stronger grasp on the language.

I would like to mention that during my research of these methods you've brought to all of our attention, I found that the flat() method takes an argument for the depth, so while you are correct that myArr.flat() will default to a depth of one, it's also possible to specify larger values, and even include an infinite option.

For example (stolen directly from the MDN web docs):

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]

var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Collapse
 
prafulla-codes profile image
Prafulla Raichurkar

Good article, thank you!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks you too for reading it.

Collapse
 
igakigongo profile image
Edward Iga Kigongo

Hi Ibrahim, thanks for the article. One thing to note is that the implementation for sort is correct but the comments are wrong.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for reading it. Now it's correct

Collapse
 
shroomlife profile image
shroomlife 🍄

great! thank you.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I think everyone know .push(), but recently I need .shift().

I think I might not need double-ended dequeue, yet.

The most important things you should emphasize, IMO, are,

  • Mutating / Non-mutating
  • Returns Array / returns something else

Some other should-know, I think, are

  • Array constructor
  • Array.from
Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Great feedback. I will do a post on it later. Thanks again :).

Collapse
 
kimsean profile image
thedevkim

I absolutely love this post. Thank you ❤️

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad you like it. Thanks for reading it

Collapse
 
russ profile image
Russ

Awesome post, thank you :). Just a curious question (junior dev), should we avoid using forEach() because it'll mutate the data?

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

forEach() is not bad, it's not like DON'T USE IT. But it depends on the use case.
If you tend to functional programming, immutability and all that kind of stuff, you should use map() more often than forEach().

forEach is preferable when you're planning to do something like logging out your data or save the data to a database. But don't change your data with forEach.
Instead, use map() when you plan to change or alternate your data. You can even use filter(), sort(), reduce() etc. in conjunction with map(). You can still do the same thing with forEach(), but it's preferable to use map() because it manipulates your data in an immutable way.
Some folks also say that map() is faster than forEach() regarding performance.
However, in the end, It depends on what you’re trying to accomplish.

Collapse
 
russ profile image
Russ

Awesome, thank you for the detailed response :)

Collapse
 
akashkava profile image
Akash Kava

Last one is wrong, myAwesomeArray.map(arr => arr * 10).flat()

It should be

myAwesomeArray.flat().map(arr => arr * 10)

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

It's not wrong. I've just followed the way flatMap() work. It applies map() first and flat() after. Therefore for the example of flat() and map() i used the same method. But if you want too you can flat the array first.

Collapse
 
akashkava profile image
Akash Kava

Error

Try it in JSFiddler, Chrome, it does not work, it is wrong !!

Thread Thread
 
ibrahima92 profile image
Ibrahima Ndaw

I've not tested with your array. You're right. Thanks for your comment.

Thread Thread
 
mikiqex profile image
Michal Novák • Edited

Sorry, but NOW it's incorrect - it was correct before. That's beacuse the flat part in flatMap() works differently, than .flat(1) alone, it only works for [[1], [2]], but not for [[1, 2]].

[[1, 2], 3, 4].flatMap(x => [x * 2])
// [NaN, 6, 8]

[[1, 2], 3, 4].map(x => [x * 2]).flat(1)
// [NaN, 6, 8]

See? flatMap will put the NaN there as well, try it for yourself.

I'd say it's either a bug in the implementation or on MDN description:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

and later:

The flatMap method is identical to a map followed by a call to flat of depth 1.

Example on MDN:

let arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]); 
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

Which translates to this one-liner:

[1, 2, 3, 4].map(x => [x * 2]).flat(1);
// [2, 4, 6, 8]

and not the other way around:

[1, 2, 3, 4].flat(1).map(x => [x * 2]);
// [[2], [4], [6], [8]]
Collapse
 
jochemstoel profile image
Jochem Stoel

I consider myself a pretty awesome JavaScript developer and often express that in my interaction with others but I honestly had never heard of Array.some().

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

It's a very handy method. It happens to everyone, we can't know everything :)