JS数组去重

简朴数组去重:

    {
      const a = [1, 3, 4, 1, 5, 2, 6, 7, 8, 3]
      const b = a.filter((item, index, self) => self.indexOf(item) === index)
      console.log(b) //[1, 3, 4, 5, 2, 6, 7, 8]
    }

实例1依据indexOf去重,indexOf的优点就是返回的是初次涌现的位置,如许背面纵然涌现的值一样,也只能返回第一次涌现的索引,固然这个只适用于简朴的数组

对象数组去重:

     const objArr = [{
        name: '称号1'
      },{
        name: '称号2'
      },{
        name: '称号3'
      },{
        name: '称号1'
      },{
        name: '称号2'
      }]

      const obj = {}
      const newObjArr = []
      for(let i = 0; i < objArr.length; i++){
         if(!obj[objArr[i].name]){
          newObjArr.push(objArr[i]);
          obj[objArr[i].name] = true
         }
      }

      console.log(newObjArr)

效果为:

     [{
        name: '称号1'
      },{
        name: '称号2'
      },{
        name: '称号3'
      }]

还可以用reduce来处置惩罚,以下:

    const objArr = [{
        name: '称号1'
      },{
        name: '称号2'
      },{
        name: '称号3'
      },{
        name: '称号1'
      },{
        name: '称号2'
      }]
      const obj = {}
      const newObjArr =  objArr.reduce((prev, curr)=>{
        obj[curr.name] ? true : obj[curr.name] = true && prev.push(curr);
        return prev
      }, [])
      console.log(newObjArr)

效果为:

     [{
        name: '称号1'
      },{
        name: '称号2'
      },{
        name: '称号3'
      }]

两个数组之间去重:

   var arr3 = [{
        id: 1,
        name: 'lily'
    }, {
        id: 2,
        name: 'hz'
    }, {
        id: 3,
        name: '123'
    }, {
        id: 4,
        name: '321'
    }, {
        id: 5,
        name: 'aa'
    }]

    var other = [{
        id: 1,
        name: 'lily'
    }, {
        id: 2,
        name: 'hz'
    }]

    isOther = (x, arr) =>{
      for(var i = 0;i<arr.length;i++){
         if(x === arr[i].id){
           return true;
         }
      }

      return false;
    }

    console.log(arr3.filter((item)=>!isOther(item.id, other)));

效果为:

   [{
        id: 3,
        name: '123'
    }, {
        id: 4,
        name: '321'
    }, {
        id: 5,
        name: 'aa'
    }]

上面例子中,在数组arr3去撤除跟数组isOther中雷同的元素,把不存在在isOther数组中的元素挑选出来

    原文作者:hope93
    原文地址: https://segmentfault.com/a/1190000017931539
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞