天天看点

js——数组扁平化处理数组扁平化去重

数组扁平化去重

Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b});

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];

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 ];

参考链接: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat