Get list of duplicate objects in an array of objects

前端 未结 7 902
你的背包
你的背包 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:31

    With lodash you can use _.groupBy() to group elements by their id. Than _.filter() out groups that have less than two members, and _.flatten() the results:

    const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
    
    const result = _.flow([
      arr => _.groupBy(arr, 'id'), // group elements by id
      g => _.filter(g, o => o.length > 1), // remove groups that have less than two members
      _.flatten // flatten the results to a single array
    ])(values);
    
    console.log(result);

提交回复
热议问题