JavaScript flat() and flatMap(): Flatten Arrays
Contents
Short answer: use arr.flat() to flatten an array one level deep, arr.flat(Infinity) to flatten it completely, and arr.flatMap(fn) when you’d otherwise write arr.map(fn).flat(). Both return a new array and leave the original alone. So does slice(), but not splice(), which changes the original array.
Below: how the depth argument works, what happens to empty slots, how to flatten an array of objects, and why flatMap() is a neat replacement for filter() + map().
flat() and the depth argument
flat(depth) pulls nested arrays up into the parent array. The default depth is 1, so only the first level of nesting is removed. Pass a bigger number to go deeper, or Infinity when you don’t know how deep the nesting goes. flat(0) leaves the nesting as it is.
const nested = [1, [2, 3], [4, [5, [6]]]];
nested.flat(); // [1, 2, 3, 4, [5, [6]]]
nested.flat(2); // [1, 2, 3, 4, 5, [6]]
nested.flat(Infinity); // [1, 2, 3, 4, 5, 6]
nested; // [1, [2, 3], [4, [5, [6]]]] unchanged
flat() removes empty slots
Sparse arrays (arrays with holes, like [1, , 3]) lose their holes when flattened, both in the outer array and in the levels being flattened. undefined and null are real values, so they stay.
[1, , 3, [4, , 6]].flat(); // [1, 3, 4, 6]
[1, undefined, null].flat(); // [1, undefined, null]
Only real arrays get flattened
flat() only unpacks elements that are actual arrays. Objects, strings and array-like objects (such as { length: 1, 0: 'a' }) are kept as single items. If you have a NodeList or similar, convert it with Array.from() first.
[['a', 'b'], 'cd', { 0: 'x', length: 1 }].flat();
// ['a', 'b', 'cd', { 0: 'x', length: 1 }]
flatMap(): map, then flatten one level
flatMap(fn) runs your callback on each item, like map(), then flattens the result by exactly one level. It’s the same as map(fn).flat(), in one pass. A typical use: turning a list of sentences into a list of words.
const sentences = ['Hello world', 'flat and flatMap'];
sentences.map(s => s.split(' '));
// [['Hello', 'world'], ['flat', 'and', 'flatMap']]
sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'flat', 'and', 'flatMap']
Flatten an array of objects
When each object holds an array, flatMap() collects all of them into one list. Empty arrays simply disappear from the result.
const orders = [
{ id: 1, items: ['apple', 'pear'] },
{ id: 2, items: ['milk'] },
{ id: 3, items: [] },
];
orders.flatMap(order => order.items);
// ['apple', 'pear', 'milk']
You can also return objects, which is handy for turning a one-to-many structure into flat rows for a table or a CSV export. Wrap the result in a Set when you only need unique values.
One row per user and tag
The inner map() returns an array of objects for each user; flatMap() merges those arrays into one.
const users = [
{ name: 'Ana', tags: ['admin', 'dev'] },
{ name: 'Ben', tags: ['dev'] },
];
users.flatMap(u => u.tags.map(tag => ({ name: u.name, tag })));
// [
// { name: 'Ana', tag: 'admin' },
// { name: 'Ana', tag: 'dev' },
// { name: 'Ben', tag: 'dev' }
// ]
[...new Set(users.flatMap(u => u.tags))]; // ['admin', 'dev']
The flatMap() map + filter trick
Because the callback’s array gets flattened, returning [] drops an item and returning [value] keeps it. That lets you filter and transform in one pass. You can also return several values to expand one item into many.
const nums = [1, -2, 3, -4, 5];
// Keep positives and double them
nums.flatMap(n => (n > 0 ? [n * 2] : [])); // [2, 6, 10]
// Same result with two passes
nums.filter(n => n > 0).map(n => n * 2); // [2, 6, 10]
// One item in, two items out
[1, 2, 3].flatMap(n => [n, n * 10]); // [1, 10, 2, 20, 3, 30]
Which one to use is mostly taste. filter().map() reads more plainly for simple cases; flatMap() wins when the keep/drop decision and the new value come from the same work, for example parsing a string and skipping the ones that fail.
flatMap() only flattens one level
Unlike flat(), flatMap() has no depth argument. If your callback returns nested arrays, only the outer one gets unpacked. Call .flat() afterwards if you need more. Returning a non-array is fine: it’s just kept as one item.
[1, 2].flatMap(n => [[n, n]]); // [[1, 1], [2, 2]]
[1, 2].flatMap(n => n * 2); // [2, 4]
Before flat(): concat and reduce
Older code flattens with concat(), which also unpacks one level. You’ll still see it, but flat() is clearer and has worked in every major browser since Chrome 69, Firefox 62 and Safari 12, and in Node.js 11+.
[].concat(...[[1, 2], [3]]); // [1, 2, 3]
[[1, 2], [3, [4]]].reduce((acc, x) => acc.concat(x), []); // [1, 2, 3, [4]]
flat() and flatMap() fit right next to the methods in 10 JavaScript array methods to simplify your code. The full parameter details are on MDN, and there are more short examples in these JavaScript tips.
FAQ
How do I flatten a deeply nested array in JavaScript?
Use arr.flat(Infinity). It flattens every level, however deep, and returns a new array.
Does flat() modify the original array?
No. Both flat() and flatMap() return a new array. The original stays as it was.
What is the difference between map() and flatMap()?
map() returns exactly one result per item, so a callback that returns arrays gives you an array of arrays. flatMap() flattens those results by one level.
Can flatMap() flatten more than one level?
No, it always flattens exactly one level. Use arr.map(fn).flat(depth) if you need more.