javascript flat sub array 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: js ,flat
const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);
console.log(flatNumbers);