flat() and flatMap()
flat() & flatMap()
Section titled “flat() & flatMap()”Introduction
Section titled “Introduction”flat() creates a new array with all sub-array elements concatenated up to a specified depth. flatMap() maps then flattens in one step.
flat()
Section titled “flat()”[1, [2, [3]]].flat(); // [1, 2, [3]] — default depth: 1[1, [2, [3]]].flat(2); // [1, 2, 3][1, [2, [3]]].flat(Infinity); // [1, 2, 3]flatMap()
Section titled “flatMap()”['hello world', 'foo bar'].flatMap(str => str.split(' '));// ['hello', 'world', 'foo', 'bar']
// Equivalent to: arr.map(...).flat()Summary
Section titled “Summary”flat(depth)flattens nested arraysflatMap()combines map + flat(1)- More efficient than separate map then flat