Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recursively convert a nested array to a flat array?

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']]));
like image 734
yiw qi Avatar asked Mar 08 '19 04:03

yiw qi


1 Answers

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))
like image 179
G.aziz Avatar answered Sep 30 '22 05:09

G.aziz