There are multiple ways to flatten a nested array. Here’s a recursive approach that works for arrays nested at any depth:
🧾 Recursive Function Example
function flattenArray(arr) {
let result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result = result.concat(flattenArray(item)); // recurse if nested
} else {
result.push(item); // push if not array
}
}
return result;
}
// Example usage:
const nested = [1, [2, [3, 4], 5], 6];
console.log(flattenArray(nested));
// Output: [1, 2, 3, 4, 5, 6]
✅ Alternative Approaches
1. Using Array.prototype.flat (ES2019+)
const nested = [1, [2, [3, 4], 5], 6];
const flattened = nested.flat(Infinity);
console.log(flattened);
// Output: [1, 2, 3, 4, 5, 6]
flat(Infinity)flattens any depth of nesting.
2. Using reduce (Functional Style)
function flatten(arr) {
return arr.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? flatten(val) : val), []
);
}
🧭 Why Recursive Works
- Checks each element: if it’s an array, recurse; otherwise, add to result.
- Handles arrays of arbitrary depth.
- Simple and readable.