0

I am sorting my object of cars. And my code hurt my brain a bit. I just want to know - can I done it better, but not in functional way?

const cars = [
  { name: 'BMW', year: 2000 },
  { name: 'Audi', year: 2000 },
  { name: 'BMW', year: 1515 },
  { name: 'BMW', year: 1111 },
  { name: 'Mercedez Benz', year: 2000 },
  { name: 'Audi', year: 2017 },
  { name: 'Honda', year: 2000 },
];
const result = {};
for (let i = 0; i < cars.length; i++) {
  if (!result.hasOwnProperty(cars[i].name)) {
    [result[cars[i].name]] = [[cars[i]]];
  } else {
    result[cars[i].name].push(cars[i]);
  }
}
console.log('result', result);

As I said I don't need to solve it functionally, because I need to do it in imperative style. So the question is - can I do something better?

Netty
  • 94
  • 5
  • 2
    like [this](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key/40774906#40774906) for example? – Nina Scholz Nov 23 '22 at 09:08
  • As I said I don't need declarative style, only imperative. – Netty Nov 23 '22 at 09:12
  • where is the problem to wrap the stuff into a function? – Nina Scholz Nov 23 '22 at 09:16
  • because I'm training to solve it by myself, not by built in array methods, that's the whole point. THANKS FOR MAKING IT "DUPLICATE" – Netty Nov 23 '22 at 09:18
  • [This answer](https://stackoverflow.com/a/51563349/479156) on the "DUPLICATE" seems to be in line with what you are looking for. – Ivar Nov 23 '22 at 09:19
  • Oh, thanks. It's actually solves my question, but I wanted smth more – Netty Nov 23 '22 at 09:22

0 Answers0