-3

I am having coming up with a logic to group similar items.

I have tried looping through the array and extracting the group value but problem I ran into was finding a way to associate it with the other key/value pair in the object.

input = [{
  group: 1,
  name: 'bob'
}, {
  group: 1,
  name: 'bob'
}, {
  group: 0,
  name: 'mike'
}]

output = [{
  1: ['bob', 'bob']
}, {
  0: ['mike']
}]
Dillan Wilding
  • 879
  • 12
  • 27
7o3
  • 43
  • 7
  • you can use .map to solve this problem – ControlAltDel Oct 15 '19 at 17:48
  • It's not an exact duplicate but it's very similar. You just need modify the last step from the answers [Group array items using object](https://stackoverflow.com/questions/31688459) – adiga Oct 15 '19 at 17:59

1 Answers1

2

let array = [{
  group: 1,
  name: "bob"
}, {
  group: 1,
  name: "bob"
}, {
  group: 0,
  name: "mike"
}];

const groupedObj = array.reduce((result, item) => {
  if (!result[item.group]) {
    result[item.group] = []
  }
  result[item.group].push(item.name)
  return result
}, {})

let grouped = (Object.entries(groupedObj)).map((item) => ({
  [item[0]]: item[1]
}))

console.log(grouped);
Ayush Gupta
  • 7,958
  • 7
  • 50
  • 85