Flatten Array
const FlattenArray = (arr) => {
return arr.reduce((prev, curr) => {
if (Array.isArray(curr)) {
prev = prev.concat(FlattenArray(curr));
} else {
prev.push(curr);
}
return prev;
}, []);
};
console.log(FlattenArray([[[1, [2]], 3, 4], [5, 6]]));
// [ 1, 2, 3, 4, 5, 6 ]
Flatten Array with Depth
const FlattenArrayWithDepth = (arr, depth = Infinity) => {
return arr.reduce((prev, curr) => {
if (Array.isArray(curr) && depth > 0) {
prev = prev.concat(FlattenArrayWithDepth(curr, depth - 1));
} else {
prev.push(curr);
}
return prev;
}, []);
};
console.log(FlattenArrayWithDepth([ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ], 0));
// [ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ]
console.log(FlattenArrayWithDepth([ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ], 1));
// [ [ 1, [ 2 ] ], 3, 4, 5, 6 ]
console.log(FlattenArrayWithDepth([ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ], 2));
// [ 1, [ 2 ], 3, 4, 5, 6 ]
console.log(FlattenArrayWithDepth([ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ], 3));
// [ 1, 2, 3, 4, 5, 6 ]
console.log(FlattenArrayWithDepth([ [ [ 1, [ 2 ] ], 3, 4 ], [ 5, 6 ] ], 10));
// [ 1, 2, 3, 4, 5, 6 ]