Lodash wasn't necessary.
In general the spread operator should only be used for forwarding arguments not for array operations.
Not quite. You should also use the spread operator when you are spreading an iterable into an array:
const unique = [...new Set(arr)]; const unique = [...a, ...b];
You might expect that concat would work, but it doesn't handle arbitrary iterables: > [].concat([1][Symbol.iterator](), [2][Symbol.iterator]())
[Array Iterator, Array Iterator]
> [...[1][Symbol.iterator](), ...[2][Symbol.iterator]()]
[1, 2]Much rather have the magic word “flat”
It's also confusing that `arr.flatMap()` is not equivalent to `arr.map().flat()`, but to `arr.map.flat(Infinity)`
x = [[[1, 2]], [[2, 3]], [[3, 4]]]
x.flatMap(x=>x)
output: [[1,2], [2,3], [3,4]]
x.map(x=>x).flat()
output: [[1,2], [2,3], [3,4]]
x.map(x=>x).flat(Infinity)
output: [1, 2, 2, 3, 3, 4]
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
> 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"I think Array#flatten should be shallow by default because it makes sense to do less work by default, it aligns with existing APIs like the DOM Node#cloneNode which is shallow by default, and it would align with the existing ES3 pattern of using Array#concat for a shallow flatten. Shallow by default would also align with flatMap too."
However, generally you don't want to operate on a list of lists and are trying to process each value one by one -- the nesting doesn't add anything. In this case, we use flatMap, which "flattens" or concatenates the interior lists so we can operate on them like it's just a big stream of values.
This is also the case for another type like `Optional`, which represents either a value `T` or the absence of a value. An optional can be "mapped" so that a function is applied only if there is a value `T` present. flatMap works the same way here, where if you want to call another method that also produces an `Optional`, flatMap will "unwrap" the optional since you never really want to work with the type `Optional<Optional<T>>`.
'map' as a function name isn't great either, since we have the same name for a data structure. What it has in its favor is being short and traditional.
JS flatMap = C# SelectMany