Array flattening concept

Array flattening

Array flattening refers to turning a multi-dimensional array into a one-dimensional array

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

achieve

1. reduce

  • Traverse each item of the array, if the value is an array, traverse recursively, otherwise concat.
function flatten(arr) {
    
      
    return arr.reduce((result, item)=> {
    
    
        return result.concat(Array.isArray(item) ? flatten(item) : item);
    }, []);
}
  • reduceIt is a method of an array. It receives a function as an accumulator. Each value in the array (from left to right) is reduced and finally calculated as a value.

  • reduceContains two parameters: callback function, the initial value passed to total

// 求数组的各项值相加的和: 
arr.reduce((total, item)=> {
    
      // total为之前的计算结果,item为数组的各项值
    return total + item;
}, 0);

2. toString & split

Call the array toStringmethod, turn the array into a string and then use the splitsplit to restore it to an array

function flatten(arr) {
    
    
    return arr.toString().split(',').map(function(item) {
    
    
        return Number(item);
    })
} 

Because spliteach item of the array formed after the division is a string, it is necessary to use a mapmethod to traverse the array and convert each item to a numeric value.

3. join & split

Like the above toString, joinyou can also convert the array to a string

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

4. Recursion

Recursively traverse each item, if it is an array, continue to traverse, otherwiseconcat

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

5. Spread operator

es6The spread operator of can turn a two-dimensional array into a one-dimensional

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

According to this result, we can do a traversal. If arr contains an array, use the spread operator once until there is no array.

function flatten(arr) {
    
    
    while(arr.some(item=>Array.isArray(item))) {
    
    
        arr = [].concat(...arr);
    }
    return arr;
}

to sum up

Although five methods have been written, there is only one core:

Traverse the array arr, if arr[i] is an array, then recursively traverse until arr[i] is not an array and then the previous result is the same concat.

Guess you like

Origin blog.csdn.net/qq_27575925/article/details/111745321
Recommended