0

I have an array of objects that has information about cars. I want to grouping on categoryId

var car = [
  { category: 1, model: "bmw" },
  { category: 1, model: "benz" },
  { category: 1, model: 'ford' }
  { category: 2, model: "kia" },
  { category: 2, model: "fiat" },
  { category: 3, model: "mg" },
];

I want this result

[  
  [
    { category: 1, model: 'bmw' },
    { category: 1, model: 'benz' },
    { category: 1, model: 'ford' }
  ],
  [ 
    { category: 2, model: 'kia' },
    { category: 2, model: 'fiat' }
  ],
  [ 
    { category: 3, model: 'mg' }
  ]
]

this is my solution but I want a way for this result based on reduce or ... I dont want to use if in forEach

let groupedCars = [];
cars.forEach((car) => {
  if (!groupedCars[car.category]) {
    groupedCars[car.category] = [];
  }
  groupedCars[car.category].push(car);
});
5
  • 1
    Your code is using arrow functions. Your code is using ES6. Commented Jan 7, 2021 at 14:54
  • I don't want use if in foreach Commented Jan 7, 2021 at 14:55
  • 1
    You can use for...of loop if you want ES6 Commented Jan 7, 2021 at 15:01
  • forEach is still ES6 btw. Commented Jan 7, 2021 at 15:10
  • "I want a way for this result based on reduce" - why? What do you think is wrong with the current code? Commented Jan 7, 2021 at 15:33

2 Answers 2

1

Solution using Array.prototype.reduce() method. Traverse the array and group it by category using reduce and at last, use Object.values() to get the result.

const car = [
  { category: 1, model: 'bmw' },
  { category: 1, model: 'benz' },
  { category: 1, model: 'ford' },
  { category: 2, model: 'kia' },
  { category: 2, model: 'fiat' },
  { category: 3, model: 'mg' },
];

const ret = Object.values(
  car.reduce((prev, c) => {
    const p = prev;
    const key = c.category;
    p[key] = p[key] ?? [];
    p[key].push({ ...c });
    return p;
  }, {})
);
console.log(ret);

Sign up to request clarification or add additional context in comments.

Comments

0

Not clear what you mean by result based on ES6. But, you could try using reduce method.

NOTE: Javascript arrays start with index 0 so, you might need to add some logic in your code to fix that

1 Comment

yes I want to use reduce or like this... how can I use of reduce to gain this result?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.