ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript flat() vs. flatMap()

@thedevspaceio

šŸ“‰ JavaScript Array flat() and flatMap() Cheatsheet

flat() and flatMap() help you flatten nested arrays and combine mapping with flattening in a single step.

āœ… flat() āœ… flatMap() āœ… When to use flat and flatMap

#javascript #arrays #flat #flatmap #flatten #functional #webdev #frontend #coding #tips


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