❤ Like
🔖 Save
🔗 Share
Eric Hu
Eric Hu

flat() vs. flatMap()

@thedevspaceio

📉 flat() vs. flatMap()

They sound similar. They look similar.

So why would JavaScript have two different methods that do almost the same thing?

This cheatsheet explains their differences, and how to use them correctly.


flat()

flat() flattens a nested array by a specified depth.

js
const nested = [1, [2, 3], [4, [5, 6]]];
 
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6]

Infinity flattens the array to any depth.

flat() also removes empty slots from sparse arrays.

js
const sparse = [1, , 3, , 5];
console.log(sparse.flat()); // [1, 3, 5]

flatMap()

flatMap() is equivalent to calling map() followed by flat(1).

It maps each element with a function, then flattens the result by one level.

js
const sentences = ["Hello world", "Goodbye moon"];
 
const words = sentences.flatMap((sentence) => sentence.split(" "));
console.log(words); // ["Hello", "world", "Goodbye", "moon"]

sentence.split(" ") splits each sentence into an array of words, producing:

js
[
  ["Hello", "world"],
  ["Goodbye", "moon"],
];

Then flatMap() flattens the result by one level, producing a single array of words:

js
["Hello", "world", "Goodbye", "moon"];

flatMap() can remove unwanted items by returning an empty array.

js
const numbers = [1, 2, 3, 4];
 
const evens = numbers.flatMap((n) => (n % 2 === 0 ? [n] : []));
console.log(evens); // [2, 4]

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io