I'm trying to sort the cars by model and month and it works well.
But I have an average month 00 which I want to be the last record of each model instead of the first.
I have no idea how to achieve this. I have created a snippet. Any help please?
let cars = [{
model: 'Ford',
month: '12'
}, {
model: 'Ford',
month: '03'
}, {
model: 'Ford',
month: '01'
}, {
model: 'Ford',
month: '00'
},
{
model: 'Ford',
month: '05'
},
{
model: 'Fiat',
month: '05'
},
{
model: 'Fiat',
month: '01'
},
{
model: 'Fiat',
month: '00'
}
];
console.log(`Unsorted cars: ${JSON.stringify(cars)}`);
const sorted = cars.sort((a, b) => a.model.localeCompare(b.model) || a.month.localeCompare(b.month));
console.log(`Sorted cars: ${JSON.stringify(sorted)}`);
Got:
[{"model":"Fiat","month":"00"},{"model":"Fiat","month":"01"},{"model":"Fiat","month":"05"},{"model":"Ford","month":"00"},{"model":"Ford","month":"01"},{"model":"Ford","month":"03"},{"model":"Ford","month":"05"},{"model":"Ford","month":"12"}]
Expected:
[{"model":"Fiat","month":"01"},{"model":"Fiat","month":"05"}, {"model":"Fiat","month":"00"},{"model":"Ford","month":"01"},{"model":"Ford","month":"03"},{"model":"Ford","month":"05"},{"model":"Ford","month":"12"}, {"model":"Ford","month":"00"}]