1、利用es6中set唯一(不能去掉重复的{})
[].from(new Set([1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]));
[...new Set([1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}])]
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}] length:13
2、es5的Array filter()+indexOf() (不能去掉重复的{})
[1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}].filter(function(elem,index,Array){
return index === Array.indexOf(elem);
})
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}] length:13
3、基础写法1(不能过滤NaN和{})
function unique(arr){
var res=[];
for(var i=0,len=arr.length;i<len;i++){
var obj = arr[i];
for(var j=0,jlen = res.length;j<jlen;j++){
if(res[j]===obj) break;
}
if(jlen===j)res.push(obj);
}
return res;
}
var arr=[1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
var ary = unique(arr);
console.log(ary)//[1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {…}, {…}] length:14
4、基础写法2(不能过滤NaN和{})
function unique(arr){
for(var i=0;i<arr.length;i++){
for(var j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
arr.splice(j,1);
j--;
}
}
}
return arr;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
var ary = unique(arr);
console.log(ary)//[1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {…}, {…}] length:14
5、利用{}的key唯一性 (能过滤{},但不能区分“NaN”和NaN)
function unique(arr) {
var obj= {};
return arr.filter(function(elem) {
return obj.hasOwnProperty(elem) ? false : (obj[elem] = true);//
});
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
var ary= unique(arr);
console.log(ary); //[1, "true", 15, false, undefined, null, NaN, 0, "a", {…}] length:10
6、利用map的key唯一性 (不能去掉重复的{})
function unique(arr){
let ary=[]
let map=new Map()
for(let i=0;i<arr.length;i++){
if(!map.get(arr[i])){
map.set(arr[i],1)
ary.push(arr[i])
}
}
return ary
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
var ary= unique(arr);
console.log(ary); //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}] length:13
7、利用reduce和includes (不能去掉重复的{})
function unique(arr){
return arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]);
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr));//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}] length:13