Remove duplicates in an object array Javascript

前端 未结 8 1081
误落风尘
误落风尘 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:17

    Plain javascript (ES2015), using Set

    const list = [{ x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 1, y: 2 }];
    
    const uniq = new Set(list.map(e => JSON.stringify(e)));
    
    const res = Array.from(uniq).map(e => JSON.parse(e));
    
    document.write(JSON.stringify(res));

    0 讨论(0)
  • 2020-12-01 16:21

    Try using the following:

    list = list.filter((elem, index, self) => self.findIndex(
        (t) => {return (t.x === elem.x && t.y === elem.y)}) === index)
    
    0 讨论(0)
  • 2020-12-01 16:22

    One liners for ES6+

    If you want to find uniq by x and y:

    arr.filter((v,i,a)=>a.findIndex(t=>(t.x === v.x && t.y===v.y))===i)
    

    If you want to find uniques by all properties:

    arr.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i)
    
    0 讨论(0)
  • 2020-12-01 16:26

    The following will work:

    var a = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];
    
    var b = _.uniq(a, function(v) { 
        return v.x && v.y;
    })
    
    console.log(b);  // [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 } ]
    
    0 讨论(0)
  • 2020-12-01 16:26

    Using lodash you can use this one-liner:

     _.uniqBy(list, e => { return e.x && e.y })
    
    0 讨论(0)
  • 2020-12-01 16:38

    Filter the array after checking if already in a temorary object in O(n).

    var list = [{ x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 1, y: 2 }],
        filtered = function (array) {
            var o = {};
            return array.filter(function (a) {
                var k = a.x + '|' + a.y;
                if (!o[k]) {
                    o[k] = true;
                    return true;
                }
            });
        }(list);
    
    document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

    0 讨论(0)
提交回复
热议问题