数组扁平化
数组扁平化:将多维数组转换为一维数组
题目1:
将数组[1, [2, [3, [4, 5]]], 6]
转换为[1, 2, 3, 4, 5, 6]
// 1.1 reduce方法
const arr = [1, [2, [3, [4, 5]]], 6];
let newArrFun = function (arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? newArrFun(cur) : cur)
}, [])
}
let newArr = newArrFun(arr);
console.log(newArr); //(6) [1, 2, 3, 4, 5, 6]
// 1.2 数组自带的扁平化方法
console.log(arr.flat(Infinity)); //(6) [1, 2, 3, 4, 5, 6]
// 1.3 利用正则表达式
let res = JSON.stringify(arr).replace(/\[|\]/g, "");
console.log(res); //1,2,3,4,5,6
console.log(res.split(","));//["1", "2", "3", "4", "5", "6"],有弊端,全为字符串
// 1.3.1 正则改进
let res2 = JSON.parse(`[${res}]`);
console.log(res2); //(6) [1, 2, 3, 4, 5, 6]
// 1.4 递归实现
const arry = [];
function fun(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fun(arr[i]);
} else {
arry.push(arr[i]);
}
}
}
fun(arr);
console.log(arry);//(6) [1, 2, 3, 4, 5, 6]
题目2:
将数组[[0], [2, 3, 4], 1, [1, [2, 3]]]
转换为[0, 2, 3, 4, 1, 1, 2, 3]
// 题2:reduce方法
let arr1 = [[0], [2, 3, 4], 1, [1, [2, 3]]];
function bian(arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? bian(cur) : cur)
}, [])
}
let newArr1 = bian(arr1);
console.log(newArr1); //[0, 2, 3, 4, 1, 1, 2, 3]
//其余方法同上