1. 普通循环
let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = unique(oldArr);
function unique(arr){
let hash=[];
for (let i = 0; i < arr.length; i++) {
if(hash.indexOf(arr[i]) === -1){
hash.push(arr[i]);
}
}
return hash;
}
2、数组下标判断法
let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = unique(oldArr);
function unique(arr){
let hash=[];
for (let i = 0; i < arr.length; i++) {
if(arr.indexOf(arr[i]) === i){
hash.push(arr[i]);
}
}
return hash;
}
3、利用filter和indexOf
function unique(arr) {
return arr.filter(function(item, index, arr) {
//返回原始数组中第一个item,其余相等的item都去掉了
return arr.indexOf(item) === index;
});
}
var arr = ['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b'];
console.log(unique(arr));// ["c", "a", "z", "x", "b"]
4.Set去重
let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = new Set(oldArr);
console.log(newArr);
console.log(newArr instanceof Array); // 此时是Set类型,不是Array
newArr = Array.from(newArr);
console.log(newArr instanceof Array);
5.利用map和扩展运算符...
let oldArr = [1, 2, 3, 4, 5, 5 , 6, 7, 8, 2, 3];
let newArr = [...new Set(oldArr)];