How To Force Reduce To NOT Sorting Alphabetically In JavaScript
I need to group by my elements in array so I did in that way: const cars = [{ make: 'vw', model: 'passat', year: '2012' }, { make: 'vw',
Solution 1:
reduceRight
applies the reduce from right to left. Just don't use the Right
variant and it'll be in the original order.
const cars = [{
make: "vw",
model: "passat",
year: "2012"
},
{
make: "vw",
model: "golf",
year: "2013"
},
{
make: "ford",
model: "mustang",
year: "2012"
},
{
make: "ford",
model: "fusion",
year: "2015"
},
{
make: "kia",
model: "optima",
year: "2012"
}
];
let group = cars.reduce((r, a) => {
r[a.make] = [...r[a.make] || [], a];
return r;
}, {});
console.log(cars)
console.log(group)
There was a bug in your original code, you were assigning properties of an array. There's no point to this; use an object instead.
Post a Comment for "How To Force Reduce To NOT Sorting Alphabetically In JavaScript"