how to flatten a 2 dimensional array in javascript code example
Example 1: flatten an array in javascript
function falltenArray(arr) {
let result = [...arr];
let flattened = false;
let counter = 0;
while (flattened === false){
if (Array.isArray(result[counter])){
result.splice(counter, 1, ...result[counter]);
counter = 0;
} else {
counter += 1;
}
if (counter === result.length){
flattened = true;
}
}
return result;
}
Example 2: flatten nested array javascript
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();