DEV Community

Shshank
Shshank

Posted on

3 1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

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()

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay