javascript flat array method code example
Example 1: javascript array flat
var arr1 = [1, 2, [3, 4]];
arr1.flat();
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
Example 2: 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;
}