-2

I want to group by the below example data in following format [{"make":"audi", "model":["r8, "rs5"]}, {"make":"ford", "model":["mustang", "fusion"]}]

//For Example

const cars = [
    {
        'make': 'audi',
        'model': 'r8',
    }, {
        'make': 'audi',
        'model': 'rs5',
    }, {
        'make': 'ford',
        'model': 'mustang',
    }, {
        'make': 'ford',
        'model': 'fusion',
    },
];


//group by in this way

[{"make":"audi", "model":["r8, "rs5"]}, {"make":"ford", "model":["mustang", "fusion"]}]


  • 2
    Here is a weirdly identical question, down to using the same model of cars as the test data https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key – Alex Aug 12 '22 at 09:45
  • 1
    Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – Alex Aug 12 '22 at 09:45
  • Though the names and values used are identical, but the groupby is different. Kindly look at it once more. – Soumik Chakraborty Aug 12 '22 at 09:47
  • Here's a [car store factory function](https://stackblitz.com/edit/js-wdfoil?file=CarStoreFactory.js) that may give you ideas. – KooiInc Aug 12 '22 at 10:10

1 Answers1

1

const cars = [
    {
        'make': 'audi',
        'model': 'r8',
    }, {
        'make': 'audi',
        'model': 'rs5',
    }, {
        'make': 'ford',
        'model': 'mustang',
    }, {
        'make': 'ford',
        'model': 'fusion',
    },
];

const output = cars.reduce((acc, obj) => {
  const outObj = acc.find(v => v.make === obj.make)
  if (!outObj) {
    acc.push({make: obj.make, model: [obj.model]})
  } else {
    outObj.model.push(obj.model)
  }
  return acc
},[])

console.log(output)
Brother58697
  • 2,290
  • 2
  • 4
  • 12
  • Please provide a code you have tried so far. This seems now you are just looking for a ready-made solution with zero effort from yourself. – Janne Aug 12 '22 at 10:01
  • 1
    @Janne My bad, I'll do that next time. Jokes aside, I think you meant to comment on the question not my answer – Brother58697 Aug 12 '22 at 10:04
  • 1
    Yes, I meant the question asked so no worries. – Janne Aug 12 '22 at 10:10