学习笔记--数组去重的常用方法

83 阅读1分钟

最近开始回顾js,针对一些知识点做一些学习归纳笔记,有许多不足的地方,望各位大佬指,及时改正。 数组去重的方法还是挺多的,一般用的最多的可能就是转set,因为最方便,还有一些其他的方法同样可以做到数组去重,在此做以下归纳。

双重循环

const arr =[1,2,1,2,3,5,6,2,5]
function Removedup(){
 let resArr =[]
 for(let i=0;i<arr.lenth;i++){
     for(let j=0;j<resArr.length;j++){
       if(arr[i]===resArr[j]){
       break;
       }
     }
     if(resArr.length===j){
     resArr.push(arr[i])
     }
 }
}

利用Indexof

利用indexof,可以简化二重循环

const arr =[1,2,1,2,3,5,6,2,5]
function Removedup(){
 let resArr =[]
 for(let i=0;i<arr.lenth;i++){
    if(resArr.indexof(arr[i])===-1){
     resArr.push(arr[i])
    }
 }
}

利用filter

indexOf返回找到指定元素的第一个索引,如果找到的元素索引和当前索引值相同,则表明该元素第一次出现。

const arr =[1,2,1,2,3,5,6,2,5]
function Removedup(){
const resArr=[]
 resArr = arr.filter((item,index)=>arr.indexOf(item)===index
 )
}

利用es6的set方法

将数组转化成set,可以去掉重复的元素,然后在转变回数组。

const arr =[1,2,1,2,3,5,6,2,5]
function Removedup(){
 const resArr = Array.from(new set(...arr))
}

使用Object.key去重 使用上述方法只针对一般的数据类型,但是如果数组中的元素具有undefined,NaN,或者对象,数组就不能完全去重了,使用indexof的时候,底层使用的是===,因为NaN===NaN为false,所以数组内查不到重复的元素,

const arr =[1,2,1,2,3,5,6,2,5]
function Removedup(){
var obj ={}
retunr arr.filter((item,index,array)=>{
return obj.hasOwnProperty((typeof item + item)?false:(obj[typeof item + item]=true)
})
}