js multidimensional array becomes one-dimensional array

1. The method used is an example

1.concat

Merges two or more arrays and returns a new array without changing the original array

const a = [1,2,3]
const b = [7,4,1]
console.log(a.concat(b))
// [1,2,3,7,4,1]

2.apply

The apply method can hijack the method of another object and inherit the properties of another object.
The apply method can accept two parameters => Function.apply(obj, args)
obj: This object will replace the this object in the Function class.
args: This is an array, which will be passed to Function as a parameter (args–>arguments)

3. Example

let arr = [[1, 2, 3], [4, 5, 6], [7, 4, 1, 8, 5, 2]]
const newArr = [].concat.apply([], arr)
console.log(newArr)
// [1,2,3,4,5,6,7,4,1,8,5,2]

2. Encapsulation function

// arr表示传入的多维数组
// dimension表示数组的维度
// isFirst传入true
const DimensionalityReduction = (arr, dimension, isFirst) => {
    
    
    if (isFirst) {
    
    
        dimension--
    }
    let newArr = [].concat.apply([], arr)  // 对数组进行降维处理
    if (dimension > 1) {
    
    
        dimension--
        DimensionalityReduction(newArr, dimension, false)  // 递归调用
        return
    }
    return newArr  // 返回结果
}

// 测试
const arr = [[1, 2, [3, 1, 2]], [4, 5, 6], [7, 4, 1, 8, 5, 2, [1, 2, 3]]]
console.log(DimensionalityReduction(arr, 3, true)) // [1,2,3,1,2,4,5,6,7,4,1,8,5,2,1,2,3]

Guess you like

Origin blog.csdn.net/weixin_45150813/article/details/121177823