简单数据去重
var arrs = [1,11,22,1,11,22,3,4,589,41,62,15,32,22,3,5,15,62,41,892];
Array.prototype.unique = function (){
var temp = {},
_arr = [],
len = this.length;
for (var i = 0; i < len; i++) {
if(!temp[this[i]]){
temp[this[i]] = this[i];
_arr.push(this[i]);
}
}
return _arr;
}
console.log(arr.unique());
简单数据去重
复杂数据根据参数去重
var arr = [
{ id: 11, title: '123' },
{ id: 2, title: '456' },
{ id: 11, title: '123' },
{ id: 3, title: '123' },
{ id: 2, title: '456' },
{ id: 1, title: '5' },
{ id: 4, title: '789' },
{ id: 4, title: '789' },
{ id: 3, title: '123' }
];
Array.prototype.attributeUnique = function(type){
var temp = {},
_arr = [],
len = this.length;
for (var i = 0; i < len; i++) {
if(!temp[this[i][type]]){
temp[this[i][type]] = this[i][type];
_arr.push(this[i]);
}
}
return _arr;
}
// 根据ID去重
console.log(arrs.attributeUnique('id'));
ID去重
// 根据Title去重
console.log(arrs.attributeUnique('title'));
Title去重
网友评论