JavaScript Interview Question #193
How would you flatten a nested array?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
JavaScript arrays provide flat(depth), which returns a new array with nested arrays flattened up to the specified depth. Infinity can be used when all nested array levels should be flattened.
Detailed Explanation
JavaScript arrays provide flat(depth), which returns a new array with nested arrays flattened up to the specified depth. Infinity can be used when all nested array levels should be flattened.
A recursive implementation is also possible and may be useful in an interview to demonstrate recursion, but the built-in method is clearer for ordinary application code.
Code Example
const nested = [
1,
[2, 3],
[4, [5, 6]]
];
console.log(nested.flat());
// [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(Infinity));
// [1, 2, 3, 4, 5, 6]