Flatten nested arrays in JavaScript
Flattens nested arrays to any depth, recursively.
function flatten(nested) {
return nested.reduce(
(flat, item) =>
flat.concat(Array.isArray(item) ? flatten(item) : item),
[],
);
}
Keywords and builtins used here
Arrayfunctionreturn
The run, in numbers
- Lines
- 7
- Characters to type
- 130
- Tokens
- 42
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 28 seconds.
Step 5 of 10 in Arrays, step 21 of 43 in Language basics.