Issue
This Content is from Stack Overflow. Question asked by asfafafags
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)}`);
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″}]
Solution
You could special-case the 00
month in your sort comparator function:
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 == '00' ? 1 : (b.month == '00' ? -1 : a.month.localeCompare(b.month)))
);
console.log(`Sorted cars: ${JSON.stringify(sorted)}`);
// alternate solution without nested ternary operator
const sorted2 = cars.sort((a, b) =>
a.model.localeCompare(b.model) ||
a.month == '00' ||
(b.month == '00' ? -1 : a.month.localeCompare(b.month))
);
console.log(`Sorted cars: ${JSON.stringify(sorted2)}`);
This Question was asked in StackOverflow by asfafafags and Answered by Nick It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.