Remove duplicates in an object array Javascript

前端 未结 8 1114
误落风尘
误落风尘 2020-12-01 16:03

I have an array of objects

list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]

And I\'m looking for an efficient way (if possible O(

8条回答
  •  执念已碎
    2020-12-01 16:40

    Vanilla JS version:

    const list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];
    
    function dedupe(arr) {
      return arr.reduce(function(p, c) {
    
        // create an identifying id from the object values
        var id = [c.x, c.y].join('|');
    
        // if the id is not found in the temp array
        // add the object to the output array
        // and add the key to the temp array
        if (p.temp.indexOf(id) === -1) {
          p.out.push(c);
          p.temp.push(id);
        }
        return p;
    
        // return the deduped array
      }, {
        temp: [],
        out: []
      }).out;
    }
    
    console.log(dedupe(list));

提交回复
热议问题