I'm trying to get this nested array to a flat array. While using this way to solve it seems every time I callback arrayFlattener(element) the newArr become a empty array. Can someone help me with this? Thank you.
const arrayFlattener = (arr) => {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let element = arr[i];
if (Array.isArray(element)){
newArr.push(arrayFlattener(element));
} else {
newArr.push(element);
}
}
return newArr;
}
console.log(arrayFlattener(['I', 'am', 'working', ['on', 'another', 'level']]));
flat
do the job with the depth
param
level specifying how deep a nested array structure should be flattened.
Example
const arr = ['I', 'am', 'working', ['on', 'another', 'level'], 'now', ["now", ["hello", "you you"]]]
console.log(arr.flat(2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With