Flatten a nested array in JavaScript
Intermediate · 3 min read
A nested array is an array with other arrays inside it, like [1, [2, 3], [4, [5]]]. They appear when you collect results from several places: pages of search results, rows of a table, replies inside comments. Often you just want one flat list, [1, 2, 3, 4, 5], so you can count, search or display everything at once.
In this tutorial you will flatten arrays with the built-in flat() method, see why its default leaves arrays behind, and then write flatten yourself with recursion so you can see how it works. Last, you will meet flatMap, a close cousin that is handy on its own. You need to know what an array, a loop and a function are.
Levels of nesting
Look at this array:
const nested = [1, [2, 3], [4, [5, [6, 7]]], 8];
1 and 8 sit at the top level. [2, 3] is one level down. [5, [6, 7]] is two levels down, and [6, 7] is three levels down. "Flattening one level" means unwrapping the arrays at the top level only. Arrays deeper inside stay as arrays.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
35 Flatten a nested array
fairTurn an array containing arrays into a single flat array. Handle nesting of any depth, and note the difference from flattening one level.
Stuck? Three hints, smallest first
- 1.
flat()flattens one level by default;flat(Infinity)goes all the way down. - 2. Writing it yourself needs recursion and
Array.isArrayper element. - 3.
flatMapismapfollowed by one level of flattening, which is handy in its own right.
Step 1: flat() and its default depth
flat() flattens an array, but by default only by one level:
const nested = [1, [2, 3], [4, [5, [6, 7]]], 8];
console.log(nested.flat()); // [ 1, 2, 3, 4, [ 5, [ 6, 7 ] ], 8 ]
[2, 3] and [4, ...] were unwrapped, but [5, [6, 7]] was not. This is the surprise most people hit. You can pass the number of levels you want, and Infinity means "keep going until nothing is nested":
const nested = [1, [2, 3], [4, [5, [6, 7]]], 8];
console.log(nested.flat(2)); // [ 1, 2, 3, 4, 5, [ 6, 7 ], 8 ]
console.log(nested.flat(Infinity)); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
flat doesn't change the original array. It returns a new one.
Step 2: one level by hand
To see what flat does, write the one-level version yourself. Walk through the items. If an item is an array, push each of its items. Otherwise push the item itself:
function flattenOnce(values) {
const out = [];
for (const v of values) {
if (Array.isArray(v)) out.push(...v);
else out.push(v);
}
return out;
}
console.log(flattenOnce([1, [2, 3], [4, [5]]])); // [ 1, 2, 3, 4, [ 5 ] ]
Array.isArray(v) is true only for arrays. ...v spreads the inner array, so push receives its items one by one instead of the whole array as a single item. The result matches flat(): one level unwrapped, [5] still inside.
Step 3: all levels with recursion
To go all the way down, flatten each inner array before spreading it. That is the same job we are already doing, on a smaller array. A function that calls itself like this is called recursive:
function flatten(values) {
const out = [];
for (const v of values) {
if (Array.isArray(v)) out.push(...flatten(v));
else out.push(v);
}
return out;
}
console.log(flatten([1, [2, 3], [4, [5, [6, 7]]], 8])); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
console.log(flatten([[[[42]]]])); // [ 42 ]
console.log(flatten([])); // []
The only change from Step 2 is flatten(v) instead of v. When flatten meets [4, [5, [6, 7]]], it calls itself on that, which calls itself on [5, [6, 7]], and so on. The recursion stops by itself: an array with no arrays inside never takes the recursive branch.
Step 4: flatMap
flatMap is map followed by one level of flattening. It is useful when each item turns into several items. Splitting sentences into words is a good example:
const words = ['hello world', 'good morning'];
console.log(words.map((s) => s.split(' '))); // [ [ 'hello', 'world' ], [ 'good', 'morning' ] ]
console.log(words.flatMap((s) => s.split(' '))); // [ 'hello', 'world', 'good', 'morning' ]
With map you get an array of arrays. flatMap hands you one flat list of words.
Step 5: a small surprise with holes
An array can have empty slots, called holes, if you skip a value between commas. flat removes them:
console.log([1, , 3].length); // 3
console.log([1, , 3].flat()); // [ 1, 3 ]
console.log([1, , 3].flat().length); // 2
You will rarely write a hole on purpose, but they can appear in arrays built with new Array(5) or by setting arr[10] on a short array. If the count of items matters, keep it in mind.
The full solution
The complete answer flattens the same nested array one level and all the way, checks the hand-written flatten against flat(Infinity), splits sentences with flatMap, and shows flat dropping a hole. Press Run to see the output.
const nested = [1, [2, 3], [4, [5, [6, 7]]], 8];
console.log('one level :', nested.flat());
console.log('all the way:', nested.flat(Infinity));
// The hand-written version, so the mechanism is visible.
function flatten(values) {
const out = [];
for (const v of values) {
if (Array.isArray(v)) out.push(...flatten(v));
else out.push(v);
}
return out;
}
console.log('by hand :', flatten(nested));
// flatMap: map then flatten one level. Useful for one-to-many.
const words = ['hello world', 'good morning'];
console.log('flatMap:', words.flatMap((s) => s.split(' ')));
// Empty slots vanish, which is occasionally surprising:
console.log('flat removes holes:', [1, , 3].flat());
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('one level only', nested.flat(), [1, 2, 3, 4, [5, [6, 7]], 8]);
test('fully flattened', nested.flat(Infinity), [1, 2, 3, 4, 5, 6, 7, 8]);
test('the hand-written version agrees', flatten(nested), nested.flat(Infinity));
test('an already flat array is unchanged', flatten([1, 2, 3]), [1, 2, 3]);
test('an empty array', flatten([]), []);
test('deeply nested single value', flatten([[[[42]]]]), [42]);
test('flatMap splits one to many', words.flatMap((s) => s.split(' ')), ['hello', 'world', 'good', 'morning']);
test('flat drops holes', [1, , 3].flat().length, 2);
The default depth of 1 catches people out: flat() on a three-deep array leaves arrays inside. Pass Infinity when you mean all of it. The last assertion is a smaller surprise — flat also removes empty slots, so [1, , 3] comes back with two elements rather than three.
Common mistakes
- Expecting
flat()to flatten everything. It goes one level by default. Useflat(Infinity)for all levels. - Pushing the inner array instead of spreading it.
out.push(v)adds the whole array as one item.out.push(...v)adds its items. - Using
mapwhen you wantedflatMap. If each item turns into a list,mapleaves you with an array of arrays.
Try it yourself
- Write
depth(values)that returns how deeply an array is nested:[1, [2]]is 2. - Use
flatMapto turn[1, 2, 3]into[1, 1, 2, 2, 3, 3]. - Change
flattento take alevelsargument, soflatten(nested, 1)matchesnested.flat().