之前最简单的写法
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
let newarr = Array.from(new Set(arr.toString().split(','))).sort((a,b)=>a-b)
//["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
arr.toString() //"1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10"
.split(',') //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "11", "12", "12", "13", "14", "10"]s
.sort((a,b)=>a-b) //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "10", "11", "12", "12", "13", "14"]
//new Set 去重 > 对象
//Array.from() 对象>数组
es10的arr.flat
Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
可以看出
arr.flat() === arr.toString().split(',') === 数组扁平化
封装一个flat,方式一
Array.prototype.flat=function(){
var arr = [];
this.forEach( k =>{
if(Array.isAttay(K)){
arr=arr.concat(k.flat()) //如果是数组,继续循环
}else{
arr.push(k)
}
})
return arr
}
封装一个flat,方式二
Array.prototype.flat = funtion(){
return this.toString()
//"1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10"
.split(',')
//["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "11", "12", "12", "13", "14", "10"]s
.sort((a,b)=>a-b)
//["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "10", "11", "12", "12", "13", "14"]
}
console.log([1,[2,[3,4]]].flat())//[1, 2, 3, 4]
网友评论