You can deep flatten an array in JavaScript by recursively calling a function that concatenates all sub-arrays into a single array until there are no more sub-arrays.
Here’s an example implementation:
function deepFlatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(deepFlatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
You can use this function like this:
const arr = [1, [2, [3, 4, [5]]], 6];
const result = deepFlatten(arr);
console.log(result); // [1, 2, 3, 4, 5, 6]
+ There are no comments
Add yours