多维数组转变为一维数组
1·join和split
join将数组拼接为字符串 split将字符串转变为数组
结果的元素为字符串,可通过map遍历处理每一项
1 let temp = [1, [2, 3], [4, 5, [6, 7]]]; 2 let res = temp.join(',').split(',') 3 let res2 = res.map((val, idx) => { 4 return Number(val) 5 }) 6 console.log(res) 7 console.log(res2)
2· 递归
1 let temp = [1, [2, 3], [4, 5, [6, 7]]]; 2 let target = [] 3 let fn = (source) => { 4 for (let i of source) { 5 if (Array.isArray(i)) { 6 fn(i) 7 } else { 8 target.push(i) 9 } 10 } 11 } 12 fn(temp) 13 console.log('递归多维数组', target)
3·flat
按照指定的深度递归遍历数组,把所有元素和遍历到的子数组中的元素合并为一个新数组返回。
a 不传参数,默认为1层,并且会过滤掉空值
b 传Infinity,相当于扁平化最深层次
let array = ['1', 2, [[3, 4], 7]]; let res = array.flat(2) console.log(res)
4·reduce和concat
1 let array = ['1', 2, [3, 4, [5, 6]], 7]; 2 let res2 = array.reduce((pre, cur) => { 3 return pre.concat(cur) 4 }, []) 5 console.log('多维数组concat', res2)
所以:concat只适合二维数组
1 let array = ['1', 2, [3, 4], 7]; 2 let res2 = array.reduce((pre, cur) => { 3 return pre.concat(cur) 4 }, []) 5 console.log('多维数组concat -- 二维', res2)
如果用concat 和reduce处理多维数组,可以递归
1 let array = ['1', 2, [[3, 4], 7]]; 2 let fn = (arr) => { 3 return arr.reduce((pre, cur) => { 4 return pre.concat(Array.isArray(cur) ? fn(cur) : cur) 5 }, []) 6 } 7 console.log('reduce', fn(array))
5·concat
二维变一维
1 let array = ['1', 2, [3, 4], 7]; 2 let res = [].concat(...array) 3 console.log(res)