DEV Community

Discussion on: 15 must-know JavaScript array methods in 2020

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]]