DEV Community

Shshank
Shshank

Posted on

flat() vs flatMap()

flat()

  • The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

  • Argument - The depth level specifying how deep a nested array structure should be flattened. Default value is 1.

  • The flat() method removes empty slots in arrays.

const arr = [10, 20, [40,5]];
console.log(arr.flat());
// [10, 20, 40, 50]

const arrTwo = [10, [[20], 30]];
console.log(arrTwo.flat());
// [10, [20], 30]

const arrThree = [10, [[20, 30]]];
console.log(arrThree.flat(2));
// [10, 20, 30]

const arrFour = [10, [[[[20, 40]]]]];
console.log(arr.flat(Infinity));
//[10, 20, 40];
Enter fullscreen mode Exit fullscreen mode

flatMap()

  • The flat flatMap() method return a new array formed by applying a given callback function to each element of the array, and then flattening the array.

  • It is identical to a map() followed by a flat().

let arr = [1, [2], 3];
const resultingArr = arr.flatMap((x) => {
return x * 3;
});
console.log(resultingArr); // [3, 6, 9]

let arrTwo = [1, [2], [[3]]];
const doubleEven = arr.flatMap((x) => {
return x % 2 == 0 ? 2 * x : [];
});
console.log(doubleEven); // [4]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sojinsamuel profile image
Sojin Samuel • Edited

First it applies map method then flat() comes into play. I've heard somewhere that, it should actually becalled mapFlat() instead of flatMap()