Removing duplicate array values and then storing them [react]

前端 未结 5 630
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:08

    Since I found the code of @Infaz 's answer used somewhere and it confused me greatly, I thought I would share the refactored function.

    function getUnique(array, key) {
      if (typeof key !== 'function') {
        const property = key;
        key = function(item) { return item[property]; };
      }
      return Array.from(array.reduce(function(map, item) {
        const k = key(item);
        if (!map.has(k)) map.set(k, item);
        return map;
      }, new Map()).values());
    }
    
    // Example
    const items = [
      { 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" },
    ];
    console.log(getUnique(items, 'id'));
    /*Output:
    [ 
      { id: 2, name: "sumit" },
      { id: 1, name: "amit" },
      { id: 3, name: "rahul" },  
      { id: 4, name: "jay" },  
      { id: 7, name: "sam" }
    ]
    */

提交回复
热议问题