Get grouped array which has same value from array using lodash

Viewed 39

I have an array like this.

[{id: 1, name: "john", item:['a']},
 {id: 1, name: "john", item:['b']},
 {id: 2, name: "linda", item:['c']},
 {id: 2, name: "linda", item:['d']},
 {id: 3, name: "liam", item:['e']}
]

I hope to get grouped arrays having same id and name value like this

[{id: 1, name: "john", item:['a']},
 {id: 1, name: "john", item:['b']}
],
[{id: 2, name: "linda", item:['c']},
 {id: 2, name: "linda", item:['d']}
],
[{id: 3, name: "liam", item:['e']}
]

Please help me

1 Answers

One solution could be to store the items in a map (for simplicity an object) based on the id and then get the values from that object. First, we have to check if we already have values stored for that id if that is the case we push the value to the array, if no we have to create the array.

const objMap = {};
items.forEach(item => {
  const {id} = item;
  if(objMap[id]) objMap[id].push(item);
  else objMap[id] = [item];
})

const groupedValues = Object.values(objMap)

I hope that this solves your problem.

Related