DEV Community

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

15 must-know JavaScript array methods in 2020

Ibrahima Ndaw on January 09, 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 properti...
Collapse
 
mdamaceno profile image
Marco Damaceno

This post could be called just "15 must-know JavaScript array methods". No need the "in 2020".

Collapse
 
idanarye profile image
Idan Arye

I don't think these methods were really necessary in 2019, but now? Can't do without them.

Collapse
 
dexygen profile image
George Jempty

I'd say they were necessary in 2018 and possibly even earlier. All these "in 2020" articles are clickbait in my opinion.

Thread Thread
 
ibrahima92 profile image
Ibrahima Ndaw

This is your opinion, and I fully respect it. However, I've added "in 2020", to just make this article easy to find for beginners. And also knowing these methods is relevant for 2020, in my opinion, because most of them introduce you to functional programming.

Thread Thread
 
surajmandalcell profile image
Suraj Mandal

I see that I tend to click more on articles which have "in 2020" in the title so I guess it works since this is what I googled for :)

Collapse
 
jochemstoel profile image
Jochem Stoel

@idan haha that is brilliant response.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I totally agree. We hear more and more functional programming in JavaScript world. And using some of these methods makes sense because they manipulate the array in an immutable way.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I think "in 2020" is more fun. No, I'm kidding. I will update the title next week to not limit it in "2020" only. Thanks for your comment

Collapse
 
itzami profile image
Rui Sousa

Leave it. It helps with the SEO and, if anything, it will show first for beginners when they search for it. It's an important article and the 2020 really doesn't hurt anyone

Thread Thread
 
ibrahima92 profile image
Ibrahima Ndaw

So, I'll let the title as it is.

Collapse
 
pszndr profile image
Paulo

I personally like includes() for transforming a code like

if (value === 1 || value === 2 || value === 3) {...}

into

if ([1, 2, 3].includes(value)) {...}

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

It's a very handy method.

Collapse
 
vsment profile image
Vasyl

Nice article.
But I am confused what is the difference between map and forEach? Output looks the same.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

map and forEach technically they do the same job. They both iterate your data holden in a given array. But under the hood they are different. map instead of manipulating the array directly, it will return a new array that contains an image of each element of the array. In the case of forEach, it will manipulate the array directly. That's the difference.

Collapse
 
vsment profile image
Vasyl

Thanks. Got it now)

Collapse
 
pszndr profile image
Paulo • Edited

map() takes a function as argument which will run on all elements on the array (getting a transformed value), and then return a new array with all transformed values.
If we run the following array through .map(x => x + 1) we get:

[1, 2, 3]
 |  |  |
 v  v  v
[2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

forEach() will just iterate on the array. Its return value is undefined.

Neither function will mutate the original array.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Great explanations and examples. Thanks again

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
 
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
 
alexdor profile image
Alexandros Dorodoulis

There is one issue with the 2nd example used in the flatmap. The .flat() call at the end isn't needed, if you run the following code you will see that it evaluates to true

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

The issue is that if you execute [1] * 10 it will return 10 and not [10] as you would expect

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

There is no issue with that code. It's just two examples.
The first is used with flatMap()

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

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

And the second uses flat() and map().

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

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

As a side note, with flatMap(), the map() function is applied first and flat() comes after.

Collapse
 
aminnairi profile image
Amin

Hi there, great article thanks!

I think you forgot about another method, which is similar to reduce: reduceRight.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

It's a handy method, but it's very similar to reduce except that reduceRight() start reducing the array from the right to the left. And for the case of reduce(), it starts from left to right. Thanks for your comment

Collapse
 
jaterlwj profile image
Jater Loh

Great article, love that every single one of them is to the point and clear.

One small typo to fix is for Number 13 (Includes), the output should be "true".

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Sorry, for the mistyping. Now it's good :). Thanks again for reading it

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
 
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
 
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
 
nerajno profile image
Nerando Johnson

Love it, please provide a place where we can go to practice all these skills.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad you like it. Maybe I'll create a github repo for that.

Collapse
 
nerajno profile image
Nerando Johnson

Appreciate it or you can just edit it and point a known resource to practice each.

Collapse
 
metalmikester profile image
Michel Renaud

Nice.

The output for 13 (includes) is wrong (copy/paste demon :)).

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Sorry, It's just a mistyping. Now it's good :)
Thanks again.

Collapse
 
metalmikester profile image
Michel Renaud

If I had $10 for each time something like that happened to me, I could buy my own country! :D

Thread Thread
 
ibrahima92 profile image
Ibrahima Ndaw

:) for sure, we have the same issue.

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
 
calvinoea profile image
Calvin

Lovely

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for reading it.

Collapse
 
imcheesecake profile image
Freddie

Love this! I needed it :D

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad it helps, and thanks again for reading it.

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

 
ibrahima92 profile image
Ibrahima Ndaw

I totally agree. I've updated the example with yours. Thanks again for your suggestion.

Collapse
 
caused profile image
Gustavo

The only difference between some() and includes() is the parameter (the former is a function, the latter an element) or Did I miss something?

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Yes, they are kinda similar. They both check if a given element exists in the array or not. They both return true or false as output.

includes() takes the element to check and optionally the starting index.

some() takes a function as a parameter.

Collapse
 
pablohzvizcarra profile image
Pablo Hernandez

Thanks for the information

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for reading it

Collapse
 
overlord_kike profile image
Enrique

Thanks for this post , it was very useful.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad you like it. Thanks for your comment

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 :)

Collapse
 
prafulla-codes profile image
Prafulla Raichurkar

Good article, thank you!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks you too for reading it.

Collapse
 
shroomlife profile image
shroomlife 🍄

great! thank you.

Collapse
 
marcossco profile image
Marcos dos Santos Carvalho

Thanks, your post is awesome.

 
ibrahima92 profile image
Ibrahima Ndaw

Even with your example, it will be not that clear. I think the difference is made by the definition. But anyway, I will update the code with your example. Thanks

Collapse
 
baloids profile image
BaloiDS

Very useful article, thanks!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad it helps. Thanks for reading it

Collapse
 
cherucole profile image
Cherucole

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

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
 
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
 
marcode_ely profile image
Marcos Aguilera Ely

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