对于前端项目开发过程中,偶尔会出现层叠数据结构的数组,我们需要将多层级数组转化为一级数组(即提取嵌套数组元素最终合并为一个数组),使其内容合并且展开。那么该如何去实现呢?
需求:多维数组=>一维数组
let list= [1, [2, [3, [4, 5]]],6];
let newList = list.flat(Infinity);
console.log(newList);
// [1,2,3,4,5,6]
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"]
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]
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]
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]
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]