JS拉平数组

JS拉平数组

有时候会遇到一个数组里边有多个数组的情况(多维数组),然后你想把它拉平使其成为一个一维数组,其实最简单的一个方法就是ES6数组方法Array.prototype.flat。使用方法如下:

const lists = [1, [2, 3, [4, 5]]];
lists.flat(); // [1, 2, 3, [4, 5]],默认只拉平一层,如果想要全部拉平,参数换为Infinity即可

可是实际有些情况下,需要去兼容低版本的问题处理,所以就自己写了两种解决方案,根据自己喜欢使用,不过没支持Infinity这个处理方式,仅是作为自定义拉平数组。

1.递归

const lists = [1, [2, 3, [4, 5]]];
function reduceArr(list, depth) {
    if(depth === 0) return list;
    let result = [];
    for(let i = 0;i < list.length;i++) {
        if(Array.isArray(list[i])) {
            result = result.concat(list[i]);
        } else {
            result.push(list[i]);
        }
    }
    return reduceArr(result, --depth);
}
console.log(reduceArr(lists, 2));

2.循环处理

const lists = [1, [2, 3, [4, 5]]];
function reduceArr(list, depth) {
    let result = [];
    for(let i = 1;i <= depth;i++) {
        result.length && (list = result);
        result = [];
        for(let j = 0;j < list.length;j++) {
            if(Array.isArray(list[j])) {
                result = result.concat(list[j]);
            } else {
                result.push(list[j]);
            }
        }
    }
    if(depth) {
        return result;
    } else {
        return list;
    }
}
console.log(reduceArr(lists, 2));
原文地址:https://www.cnblogs.com/ljwk/p/11498128.html