1.借助json对象对数组进行去重,并计算重复的次数
Array.prototype.unique = function (){
var key = {};
var narr = [];
var len = this.length;
for( var i=0; i<len; i++ ){
var t = this[i];
( key[t] || t == undefined )?key[t]=key[t]+1:key[t] = 1;narr.push(t);
}
console.log(key);
return narr;
}
2.json数组去重,获取没重复的最右一值放入新数组
唯一的key名,根据此键名进行去重,保证键名的唯一;
如果不存在key则只能是常规数组去重,例如[1,2,3,2,3,1,3,3,3,3,3,3]
var unique = function (arr, key) {
var r = [];
for (var i = 0, l = arr.length; i < l; i++) {
for (var j = i + 1; j < l; j++) {
if (key) {
if (arr[i][key] === arr[j][key]) {
j = ++i;
}
}
else {
if (arr[i] === arr[j]) {
j = ++i;
}
}
}
r.push(arr[i]);
}
return r;
};
var arr = [1,2,3,2,3,1,3,3,3,3,3,3];