1、Filter()方法
let arr = [1,1,2,3,4,5,5,6]
let arr2 = arr.filter(function(item,index) {
return arr.indexOf(item) === index
})
2、Reduce()方法
let arr = [1,1,2,3,4,5,5,6]
let arr2 = arr.reduce(function(rs, cur) {
if(!rs.includes(cur)) {
rs.push(cur)
}
return rs
}, [])
3、ES6 的 Set
let arr = [1,1,2,3,4,5,5,6]
let arr2 = [...new Set(arr)]
End
1. 高效快速的数组去重
Array.prototype.uniquer = function() {
var hash = {},
newarr = [],
type;
for (var i = 0; i < this.length; i++) {
type = typeof(this[i])
if (!hash[this[i]]) {
newarr.push(this[i]);
hash[i] = type;
} else if (hash[this[i]].indexOf(type) < 0) {
newarr.push(this[i]);
hash[i] = type;
}
}
return newarr;
}
var a = [1, 2, '1', 3, 4, 1];
var b = a.uniquer();
console.log(b);
[1, 2, "1", 3, 4]