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?