js数组去重方法(处理{}和NaN结果不同)

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

4、基础写法2(不能过滤NaN和{})

function unique(arr){
    for(var i=0;i

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

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

你可能感兴趣的:(js数组去重方法(处理{}和NaN结果不同))