Collect unique objects in JavaScript array

前端 未结 4 705
梦毁少年i
梦毁少年i 2020-12-12 02:22

Suppose I have following arrays of objects

var firstDataSet = [
  {\'id\': 123, \'name\': \'ABC\'},
  {\'id\': 456, \'name\': \'DEF\'},
  {\'id\': 789, \'nam         


        
4条回答
  •  轮回少年
    2020-12-12 02:47

    This can be achieved By extending Set class Like below

        var firstDataSet = [
          {'id': 123, 'name': 'ABC'},
          {'id': 456, 'name': 'DEF'},
          {'id': 789, 'name': 'GHI'},
          {'id': 101, 'name': 'JKL'}
        ];
    
        var secondDataSet = [
          {'id': 123, 'name': 'ABC', 'xProp': '1q'},
          {'id': 156, 'name': 'MNO', 'xProp': '2w'},
          {'id': 789, 'name': 'GHI', 'xProp': '3e'},
          {'id': 111, 'name': 'PQR', 'xProp': '4r'}
        ];
    
        Array.prototype.unshift.apply(firstDataSet , secondDataSet );
    
        //console.log(firstDataSet)
    
        class UniqueSet extends Set {
                constructor(values) {
                    super(values);
    
                    const data = [];
                    for (let value of this) {
                        if (data.includes(JSON.parse(value.id))) {
                            this.delete(value);
                        } else {
                            data.push(value.id);
                        }
                    }
                }
              }
    
    console.log(new UniqueSet(firstDataSet))
    

    Working link

提交回复
热议问题