345 字
2 分钟
数组扁平化常用方法
①递归处理:milky_way:
Array.prototype.flatten = function () {
let res = []
let len = this.length
for(let i=0;i<len;i++){
if(Array.isArray(this[i])){
res = res.concat(this[i].flatten())
}else {
res.push(this[i])
}
}
return res
}
let arr=[1,2,3,[4,5,'hello',['world',9,666]]]
console.log(arr.flatten()) // [1, 2, 3, 4, 5, 'hello', 'world', 9, 666]
②数组的reduce
方法:milky_way:
function flatten(arr) {
return arr.reduce((prev,item) => {
return prev.concat(Array.isArray(item) ? flatten(item) : item)
},[])
}
let arr=[1,2,3,[4,5,'hello',['world',9,666]]]
console.log(flatten(arr)) // [1, 2, 3, 4, 5, 'hello', 'world', 9, 666]
③利用数组的join
和split
方法:milky_way:
let arr = [4, 1, 2, 3, 6, [7, 8, [3, 9, 10, [4, 6, 11]]]]
let res = arr.join(',').split(',').map(Number)
console.log(res) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
④利用正则方法:milky_way:
let arr = [4, 1, 2, 3, 6, [7, 8, [3, 9, 10, [4, 6, 11]]]]
let res = arr.join(',').replace(/\[|\]/g,"").split(',').map(Number)
console.log(res) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
⑤ES6
新方法flat()
:milky_way:
TIP 实现数组的”拉平”(扁平化),该方法返回一个新数组,对原数据没有影响。
具有一个可选参数
depth
,用来指定深度,默认为1 传入’Infinity’可以拉平任意深度的数组
let arr = [4, 1, 2, 3, 6, [7, 8, [3, 9, 10, [4, 6, 11]]]]
console.log(arr.flat()) // [4, 1, 2, 3, 6, 7, 8, [3, 9, 10, [4, 6, 11]]]
console.log(arr.flat(2)) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, [4, 6, 11]]
console.log(arr.flat(Infinity)) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
⑥利用...
扩展运算符循环:milky_way:
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten([4, 1, 2, 3, 6, [7, 8, [3, 9, 10, [4, 6, 11]]]])) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]