Get list of duplicate objects in an array of objects

前端 未结 7 860
你的背包
你的背包 2020-12-14 22:11

I am trying to get duplicate objects within an array of objects. Let\'s say the object is like below.

values = [
  { id: 10, name: \'someName1\' },
  { id: 1         


        
相关标签:
7条回答
  • 2020-12-14 22:48

    You can use Array#reduce to make a counter lookup table based on the id key, then use Array#filter to remove any items that appeared only once in the lookup table. Time complexity is O(n).

    const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
    
    const lookup = values.reduce((a, e) => {
      a[e.id] = ++a[e.id] || 0;
      return a;
    }, {});
    
    console.log(values.filter(e => lookup[e.id]));

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