zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

前端面试 【JavaScript】— JS中将数组扁平化有哪些方法?

2023-03-15 23:26:04 时间

对于前端项目开发过程中,偶尔会出现层叠数据结构的数组,我们需要将多层级数组转化为一级数组(即提取嵌套数组元素最终合并为一个数组),使其内容合并且展开。那么该如何去实现呢?

需求:多维数组=>一维数组

1. 调用ES6中的flat方法

let list= [1, [2, [3, [4, 5]]],6];

let newList = list.flat(Infinity);
console.log(newList);
// [1,2,3,4,5,6]

2. replace + split

let list= [1, [2, [3, [4, 5]]],6];

let str = JSON.stringify(list);
let newList = str.replace(/([|])/g, '').split(',');
console.log(newList);
// ["1", "2", "3", "4", "5", "6"]

3. replace + JSON.parse

let list= [1, [2, [3, [4, 5]]],6];

let str = JSON.stringify(list);
str = str.replace(/([|])/g, '');
str = '['+str+']';
let newList=JSON.parse(str);
console.log(newList);
// [1, 2, 3, 4, 5, 6]

4. 普通递归

let list= [1, [2, [3, [4, 5]]],6];

let result= [];
let fn=function(list) {
    for(let i=0; i<list.length; i++) {
        let item=list[i];
        if (Array.isArray(list[i])){
            fn(item);    
        } else {
            result.push(item);    
        }  
    }
};
fn(list);
console.log(result);
// [1, 2, 3, 4, 5, 6]

5. 利用reduce函数迭代

let list= [1, [2, [3, [4, 5]]],6];

function flat(list) {
    return list.reduce((pre, cur) => {
        return pre.concat(Array.isArray(cur)?flat(cur):cur);    
    }, []);
};
let newList = flat(list);
console.log(newList);
//  [1, 2, 3, 4, 5, 6]

6. 扩展运算符

let list= [1, [2, [3, [4, 5]]],6];
while (list.some(Array.isArray)) {
    // 将多维数组逐渐展开拼接
    list=[].concat(...list);
};
console.log(list);
// [1, 2, 3, 4, 5, 6]