Sort simple array with a simple condition (Snippet Included)

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

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?