flatten javascript array code example
Example 1: javascript array flat
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
Example 2: flatten an array in javascript
function flatten(arr) {
const result = []
arr.forEach((i) => {
if (Array.isArray(i)) {
result.push(...flatten(i))
} else {
result.push(i)
}
})
return result
}
// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]