Get list of duplicate objects in an array of objects

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

    With lodash you can solve this with filter and countBy for complexity of O(n):

    const data = [{ id: 10,name: 'someName1' }, { id: 10,name: 'someName2' }, { id: 11,name: 'someName3' }, { id: 12,name: 'someName4' } ]
    
    const counts = _.countBy(data, 'id')
    console.log(_.filter(data, x => counts[x.id] > 1))

    You could do the same with ES6 like so:

    const data = [{ id: 10,name: 'someName1' }, { id: 10,name: 'someName2' }, { id: 11,name: 'someName3' }, { id: 12,name: 'someName4' } ]
    
    const countBy = (d, id) => d.reduce((r,{id},i,a) => (r[id] = a.filter(x => x.id == id).length, r),{})
    const counts = countBy(data, 'id')
    console.log(data.filter(x => [x.id] > 1))

提交回复
热议问题