将一个多维数组转成一维数组,例如 [2, 3, [5, 1], 8, [9, [4,6,[0]]], 7] ===> [2, 3, 5, 1, 8, 9, 4, 6, 0, 7]
方法一、递归
直接输出新数组的写法:
let arr = [2, 3, [5, 1], 8, [9, [4,6,[0]]], 7];
let newArr = [];
function flattener(arr) {
arr.forEach(ele => {
if(Array.isArray(ele)){
flattener(ele)
}else {
newArr.push(ele);
}
});
}
flattener(arr);
// console.log(newArr)
// [2, 3, 5, 1, 8, 9, 4, 6, 0, 7]
return 新数组的写法:
let arr = [2, 3, [5, 1], 8, [9, [4,6,[0]]], 7];
function flattener(arr, newArr) {
arr.forEach(ele => {
if(Array.isArray(ele)){
flattener(ele, newArr)
}else {
newArr.push(ele);
}
});
return newArr;
}
let myNewArr = flattener(arr, []);
// console.log(myNewArr);
// => [2, 3, 5, 1, 8, 9, 4, 6, 0, 7[]
方法二、while+es6扩展语法
let arr = [2, 3, [5, 1], 8, [9, [4,6,[0]]], 7];
function flattener(arr) {
while(arr.some(item=>Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
let newArr = flattener(arr);
// console.log(newArr);
// => [2, 3, 5, 1, 8, 9, 4, 6, 0, 7[]
方法三 、reduce
let arr = [2, 3, [5, 1], 8, [9, [4,6,[0]]], 7];
function flattener(arr) {
return arr.reduce((result, currentValue)=> {
return result.concat(Array.isArray(currentValue) ? flattener(currentValue) : currentValue);
}, []);
}
// console.log(flattener(arr));
// => [2, 3, 5, 1, 8, 9, 4, 6, 0, 7[]