《数组降维方法总结》


2020-05-31 上次更新时间:12/8/2020, 6:08:34 PM 0 javascript

# 1. Array.prototype.flat()

es6 新增数组方法。Array.prototype.flat()

缺点:需要计算数组的维度

var arr = [ 1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]

arr.flat(4);  // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,{'name': 'jack'}]
1
2
3

# 2. 数组字符串化

缺点:数组内对象无法转换

var arr = [ 1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]

arr += '';
arr = arr.split(',');

arr; // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,[object Object]]
1
2
3
4
5
6

使用 Infinity 作为深度,展开任意深度的嵌套数组

var arr = [ 1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]

arr.flat(Infinity);   // [1,2,21,22,221,2211,2212,3,31,32,33,331,4,{'name': 'jack'}]
1
2
3

# 3. 递归

var arr = [ 1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]

function reduceDimension(arr) {
    let result = [];
    let toArr = function(arr) {
        arr.forEach(function(item) {
            item instanceof Array ? toArr(item) : result.push(item)
        })
    }
    toArr(arr);
    return result;
}

reduceDimension(arr);
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 4. reduce + concat + 递归

var arr = [ 1, [2, 21, [22, 221, [2211, 2212]]], [3, [31, 32, [33, 331]]], 4, {'name': 'jack'}]

function reduceDimension(arr) {
   return arr.reduce(function(prev, next){
       return Array.isArray(next) ? prev.concat(flattenDeep(next)) : prev.concat(next)
   }, [])
}

reduceDimension(arr);
1
2
3
4
5
6
7
8
9
上次更新时间: 12/8/2020, 6:08:34 PM