数组去重
//哈希表去重
var arr1=[1,3,5,2,1,4,3,1,2,5,3,1,2,1];
function delectRepeat(arr1) {
var len = arr1.length;
var arr = [];
for(var i = 0; i < len; i++)
if(arr.indexOf(arr1[i]) == -1)
arr.push(arr1[i]);
return arr;
}
console.log(delectRepeat(arr1));
//ES6 Set去重
function delectRepeat1(arr){
var x = new Set(arr);
return x;
}
console.log(delectRepeat1(arr1));
//数组下标判断
//如果当前数组的第 i 项在当前数组中第一次出现的位置不是 i,那么表示第 i 项是重复的,忽略掉。否则存入结果数组。
function delectRepeat2(arr){
var arr1=[];
for (var i = 0; i < arr.length; i++) {
if(arr.indexOf(arr[i])==i){
arr1.push(arr[i]);
}
}
return arr1;
}
console.log(delectRepeat2(arr1));
//使用对象保存重复出现次数保存
function delectRepeat3(arr){
var obj = {};
for(var i = 0; i < arr.length; i++){
if(!obj[arr[i]])
obj[arr[i]] = 1;
else
obj[arr[i]]++;
}
return obj;
}