题目描述:
将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数组
解题:
- 思路一: ```javascript Array.prototype.flat= function() { return [].concat(…this.map(item => (Array.isArray(item) ? item.flat() : [item]))); }
Array.prototype.unique = function() { return […new Set(this)] }
const sort = (a, b) => a - b;
console.log(arr.flat().unique().sort(sort)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
+ 思路二:
```javascript
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]
// 扁平化
let flatArr = arr.flat(4)
// 去重
let disArr = Array.from(new Set(flatArr))
// 排序
let result = disArr.sort(function(a, b) {
return a-b
})
console.log(result)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
扩展阅读: