js数组去重

1 answer=collection=>{
2     let res = collection.filter((element,index,self)=>{return self.indexOf(element)===index});
3     return res;
4 }
5 console.log(answer([1,1,NaN,NaN]))

结果为:

方法二:

1 answer = collection =>{
2     let res = [];
3     for(let i = 0;i<collection.length;i++){
4         if(collection.indexOf(collection[i])===i){res.push(collection[i])}
5     }
6     return res;
7 }
8 console.log(answer([1,1,NaN,NaN]))

结果:同上

方法三:

 1 answer = collection=>{
 2     for(let i =0;i<collection.length-1;i++){
 3         for(let j =i+1;j<collection.length;j++){
 4             if(collection[i]==collection[j]){
 5                 collection.splice(j,1);
 6                 j--;
 7             }
 8         }
 9     }
10     return collection;
11 }
12  console.log(answer([1,1,NaN,NaN]))

结果:

方法四:

1 answer = collection=>{
2     return Array.from(new Set(collection))
3 }
4 console.log(answer([1,1,NaN,NaN]))

结果为:

方法五:

1 answer = collection=>{
2     const res = new Map();
3     return collection.filter((a)=>!res.has(a)&&res.set(a,1))
4 }
5 console.log(answer([1,1,NaN,NaN]))

结果:同方法四

 写在最后:虽然都是数组去重,但是由于方法不一样,在处理特殊数据时结果也不一样,在处理普通数据(数字,字符串)结果是一样的

posted @ 2018-02-28 22:54  gaoxuerong  阅读(153)  评论(0编辑  收藏  举报