JavaScript基础 - 数组扁平化/降维的4种方法

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'}]

使用 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'}]

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]]

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);

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);

你可能感兴趣的:(前端,javascript)