Array.prototype.flat #
The array in this example is several levels deep: it contains an array which in turn contains another array.
const array = [1, [2, [3]]];
Array#flat returns a flattened version of a given array.
array.flat();
array.flat(1);
The default depth is 1, but you can pass any number to recursively flatten up to that depth. To keep flattening recursively until the result contains no more nested arrays, we pass Infinity.
array.flat(Infinity);
Why is this method known as Array.prototype.flat and not Array.prototype.flatten? Read our #SmooshGate write-up to find out!
Array.prototype.flatMap #
Here’s another example. We have a duplicate function that takes a value, and returns an array that contains that value twice. If we apply duplicate to each value in an array, we end up with a nested array.
const duplicate = (x) => [x, x];
[2, 3, 4].map(duplicate);
You can then call flat on the result to flatten the array:
[2, 3, 4].map(duplicate).flat();
Since this pattern is so common in functional programming, there’s now a dedicated flatMap method for it.
[2, 3, 4].flatMap(duplicate);
flatMap is a little bit more efficient compared to doing a map followed by a flat separately.
Interested in use cases for flatMap? Check out Axel Rauschmayer’s explanation.
Array#{flat,flatMap} support #