Intermediate · 16 of 17 · 13 min read
Flattening nested arrays
What flat does and does not do by default, the recursive and reduce versions interviewers ask for, and flatMap as the one-level shortcut.
- Arrays
Flattening turns [1, [2, [3]]] into [1, 2, 3]. It is a stock interview exercise because the
one-liner is trivial and the hand-written version tests recursion, reduce and Array.isArray at
once.
flat
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat()); // [1, 2, [3, [4]]] — one level
console.log(nested.flat(2)); // [1, 2, 3, [4]]
console.log(nested.flat(3)); // [1, 2, 3, 4]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4] — any depth
console.log(nested); // [1, [2, [3, [4]]]] — untouched
The depth argument has a few edge cases worth knowing, because each one looks like a bug when you meet it:
const nested = [1, [2, [3]]];
console.log(nested.flat(0)); // [1, [2, [3]]] — a shallow copy, nothing flattened
console.log(nested.flat(-1)); // [1, [2, [3]]] — negatives clamp to 0
console.log(nested.flat(true)); // [1, 2, [3]] — coerced to 1
console.log(nested.flat('2')); // [1, 2, 3] — coerced to 2
console.log(nested.flat(0) === nested); // false — still a new array
flat also removes holes from a sparse array, which is a handy side effect:
const sparse = [1, , 3]; // a hole at index 1
console.log(sparse.length); // 3
console.log(sparse.flat()); // [1, 3] — holes dropped
console.log(sparse.flat().length); // 2
flatMap
map followed by one level of flat, in a single pass:
const sentences = ['hello world', 'goodbye'];
console.log(sentences.map((s) => s.split(' '))); // [["hello","world"],["goodbye"]]
console.log(sentences.flatMap((s) => s.split(' '))); // ["hello","world","goodbye"]
console.log(sentences.map((s) => s.split(' ')).flat()); // the same result
It flattens one level only, so a callback that returns nested arrays still leaves nesting:
console.log([1, 2].flatMap((n) => [[n * 10]])); // [[10], [20]] — one level removed, one left
Its best trick is filtering and mapping together: return [] to drop an item, [x] to keep one, or
several elements to expand one input into many.
const nums = [1, 2, 3, 4, 5];
console.log(nums.flatMap((n) => (n % 2 ? [n * 10] : []))); // [10, 30, 50]
console.log(nums.flatMap((n) => [n, n])); // [1,1,2,2,3,3,4,4,5,5]
const rows = [
{ id: 1, tags: ['a', 'b'] },
{ id: 2, tags: [] },
];
console.log(rows.flatMap((r) => r.tags)); // ["a", "b"] — collect a nested field
Writing it yourself
The version the exercise is actually asking for.
Recursive
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) {
out.push(...flatten(item)); // recurse into the nested array
} else {
out.push(item);
}
}
return out;
}
console.log(flatten([1, [2, [3, [4, [5]]]]])); // [1, 2, 3, 4, 5]
console.log(flatten([])); // []
console.log(flatten([[], [[]]])); // [] — empties vanish
Array.isArray is the right test. typeof item === 'object' is true for null, for a Date and
for every plain object, so it flattens things you did not mean to touch.
console.log(typeof [] === 'object'); // true — useless as a test
console.log(Array.isArray([])); // true
console.log(Array.isArray('ab')); // false — a string is not flattened
console.log(flatten([1, 'ab', null, { a: 1 }])); // [1, "ab", null, { a: 1 }]
With reduce
The same logic, written as a fold — this is the version most often shown in answers:
const flatten = (arr) =>
arr.reduce(
(out, item) => (Array.isArray(item) ? out.concat(flatten(item)) : out.concat(item)),
[],
);
console.log(flatten([1, [2, [3]]])); // [1, 2, 3]
concat does one level of flattening itself when handed an array, so the Array.isArray test can
even be dropped — though keeping it makes the intent obvious:
const flattenConcat = (arr) =>
arr.reduce((out, item) => out.concat(Array.isArray(item) ? flattenConcat(item) : item), []);
console.log(flattenConcat([1, [2, [3]]])); // [1, 2, 3]
Be aware that concat and [...out, …] both copy the accumulator on every step, making these
versions O(n²). push into the accumulator is the linear form:
const flattenFast = (arr) =>
arr.reduce((out, item) => {
if (Array.isArray(item)) out.push(...flattenFast(item));
else out.push(item);
return out; // the same array each time
}, []);
console.log(flattenFast([1, [2, [3]]])); // [1, 2, 3]
To a given depth
The full version of flat, which is a good follow-up answer:
function flattenDepth(arr, depth = 1) {
if (depth < 1) return arr.slice();
return arr.reduce(
(out, item) =>
out.concat(Array.isArray(item) ? flattenDepth(item, depth - 1) : item),
[],
);
}
console.log(flattenDepth([1, [2, [3, [4]]]])); // [1, 2, [3, [4]]]
console.log(flattenDepth([1, [2, [3, [4]]]], 2)); // [1, 2, 3, [4]]
console.log(flattenDepth([1, [2, [3, [4]]]], Infinity)); // [1, 2, 3, 4]
Without recursion
Worth having, because it cannot overflow the stack — and because “now do it iteratively” is the standard follow-up:
function flattenIterative(input) {
const stack = [...input];
const out = [];
while (stack.length > 0) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item); // put its elements back to be examined
} else {
out.push(item);
}
}
return out.reverse(); // popping from the end reversed the order
}
console.log(flattenIterative([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
The reverse at the end is the detail people miss: pop takes from the end, so the results come out
backwards.
| Approach | Depth | Stack-safe | Notes |
|---|---|---|---|
arr.flat(Infinity) |
all | yes | what you write in real code |
recursion with push |
all | no | the expected interview answer |
reduce + concat |
all | no | elegant, O(n²) |
| explicit stack | all | yes | the “no recursion” answer |
flatMap |
one | yes | map and flatten together |
Common mistakes
Expecting flat() to go all the way
Mistake. deeplyNested.flat() and wondering why arrays remain.
Why it fails. The default depth is 1.
What to do instead. flat(Infinity), or pass the depth you need.
Discarding the return value
Mistake. nested.flat(); on its own line, then using nested.
Why it fails. flat is a copying method — the original array is never modified.
What to do instead. Assign it: const flatArray = nested.flat().
Using typeof to detect an array
Mistake. if (typeof item === 'object') recurse(item).
Why it fails. null, Date objects and plain objects all pass that test, so the function
recurses into things that are not arrays — and null throws.
What to do instead. Array.isArray(item).
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
flat takes a depth argument, and its default is not "all the way down".
What does this log?
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat());How do you flatten an array whose nesting depth you do not know?
What is the difference between arr.flatMap(fn) and arr.map(fn).flat()?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.