JavaScript flat() vs. flatMap()
š 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.
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.
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.
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:
[
["Hello", "world"],
["Goodbye", "moon"],
];Then flatMap() flattens the result by one level, producing a single array of words:
["Hello", "world", "Goodbye", "moon"];flatMap() can remove unwanted items by returning an empty array.
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.