3 ms·
I wonder if there are enough use-cases for .flat to not default to Infinity. It's also confusing that `arr.flatMap()` is not equivalent to `arr.map().flat()`,
by dmitriid 7y ago
I wonder if there are enough use-cases for .flat to not default to Infinity.
It's also confusing that `arr.flatMap()` is not equivalent to `arr.map().flat()`, but to `arr.map.flat(Infinity)`
- Ravengenocide 7y agoAccording to MDN `arr.flatMap()` is indeed equivalent to `arr.map().flat()` (without the Infinity). [1] Testing in the Chrome Devtools it also seems to be the case: 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/Reference/Global_Objects/Array/flatMap 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
- kevlened 7y agoInfinity was originally the default (which feels intuitive), but here's the argument for changing it [0]: "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." [0] https://github.com/tc39/proposal-flatMap/issues/9 https://github.com/tc39/proposal-flatMap/issues/9