Default first parameter for Array.flatMap function

The Array.flatMap() function is used to simplify array lists by reducing one level of iteration between the elements in the list, ex:

console.log([[1, 2], 3].flatMap(item => item))
// output: [1, 2, 3]

The problem is that I necessarily need to pass a minimal function like item => item for this function to work.

I believe this function could work like the Array.sort() function which, if it does not receive any predicate, performs the default sorting like this:

console.log([2, 1, 3].sort())
// output: [1, 2, 3]

With this improvement, the Array.flatMap() function could be used like:

console.log([[1, 2], 3].flatMap())
// output: [1, 2, 3]

Do you want [[1, 2], 3].flat(1)?

2 Likes

I didn't know Array.flat() did what I expected, thanks!

You're also mistaken about how sort works. That code will behave surprisingly once you have numbers with different numbers of digits.