var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
要求将数组扁平化 + 去重 + 升序
方法1:Array.prototype.flat(1)不填默认是展开1层,也可以传Infinity展开无论多少层
Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{return a-b})
方法2:扩展属性扁平化、唯一、排序。其中扁平化用递归
Array.prototype.falt = function() {
return [].concat(...this.map(item => (Array.isArray(item) ? item.falt() : [item])));
}
Array.prototype.unique = function() {
return [...new Set(this)]
}
const sort = (a, b) => a - b;
console.log(arr.falt().unique().sort(sort));
对上面的粗暴写法如下:
let flatArr = arr.flat(4)
let disArr = Array.from(new Set(flatArr))
let result = disArr.sort(function(a, b) { return a-b })
网友评论