Removing duplicate array values and then storing them [react]

前端 未结 5 627
Happy的楠姐
Happy的楠姐 2021-02-06 16:49

I\'m trying to strip the duplicate array values from my current array. And I\'d like to store the fresh list (list without duplicates) into a new variable.

var          


        
5条回答
  •  [愿得一人]
    2021-02-06 17:05

    If you want to remove duplicate values which contains same "id", You can use this.

    const arr = [
      { id: 2, name: "sumit" },
      { id: 1, name: "amit" },
      { id: 3, name: "rahul" },
      { id: 4, name: "jay" },
      { id: 2, name: "ra one" },
      { id: 3, name: "alex" },
      { id: 1, name: "devid" },
      { id: 7, name: "sam" },
      ];
    

    function getUnique(arr, index) {
    
      const unique = arr
           .map(e => e[index])
    
           // store the keys of the unique objects
           .map((e, i, final) => final.indexOf(e) === i && i)
    
           // eliminate the dead keys & store unique objects
          .filter(e => arr[e]).map(e => arr[e]);      
    
       return unique;
    }
    
    console.log(getUnique(arr,'id'))
    

    Result :

    > Array 
    [ 
      { id: 2, name: "sumit" },
      { id: 1, name: "amit" },
      { id: 3, name: "rahul" },  
      { id: 4, name: "jay" },  
      { id: 7, name: "sam" }
    ]
    

提交回复
热议问题