当前位置:网站首页>[JS] array flattening

[JS] array flattening

2022-06-13 06:14:00 A strong foam

Concept

Array flattening refers to changing a multidimensional array into a one-dimensional array

[1, [2, 3, [4, 5]]]  ------>    [1, 2, 3, 4, 5]

Realization

1. Extension operator

es6 The extension operator can change a two-dimensional array into one-dimensional

[].concat(...[1, 2, 3, [4, 5]]);  // [1, 2, 3, 4, 5]

Based on this result, we can do a traversal , if arr If there is an array in, use the one-time extension operator , Until there is no .

function flatten(arr) {
    
    while(arr.some(item=>Array.isArray(item))) {
    
        arr = [].concat(...arr);
    }
    return arr;
}
console.log(flatten([1, [2, 3, [4, 5]]])) // [1, 2, 3, 4, 5]

2. reduce

Traverse every item in the array , If the value is an array, recursively traverse , otherwise concat.

function flatten(arr) {
      
    return arr.reduce((result, item)=> {
    
        return result.concat(Array.isArray(item) ? flatten(item) : item);
    }, []);
}
3. recursive

Recursively traverse every item , If it's an array, continue traversing , otherwise concat.

function flatten(arr) {
    
    var res = [];
    arr.map(item => {
    
        if(Array.isArray(item)) {
    
            res = res.concat(flatten(item));
        } else {
    
            res.push(item);
        }
    });
    return res;
}
4. toString & split

Call array toString Method , Change the array to character string then Reuse split Division Revert to array .

function flatten(arr) {
    
    return arr.toString().split(',').map(function(item) {
    
        return Number(item);
    })
} 
console.log(flatten([1, [2, 3, [4, 5]]])) // [1, 2, 3, 4, 5]

Add :

console.log([1, [2, 3, [4, 5]]].toString()) // 1,2,3,4,5

5. join & split

And the above toString equally ,join You can also convert arrays to strings .

function flatten(arr) {
    
    return arr.join(',').split(',').map(function(item) {
    
        return parseInt(item);
    })
}

summary

The core :

(1) Traversal array arr, if arr[i] For arrays, recursively traverse , until arr[i] Not for arrays and then with previous results concat.

(2) Convert to string , Reprocessing .

(3) Extension operator .

原网站

版权声明
本文为[A strong foam]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270556508544.html