Sortying array by two criteria

Tags: ,



I have array like this:

const array = [{
    id: 1,
    date: 591020824000,
    isImportant: false,
  },
  {
    id: 2,
    date: 591080224000,
    isImportant: false,
  },
  {
    id: 3,
    date: 591080424000,
    isImportant: true,
  },
  {
    id: 4,
    date: 591080225525,
    isImportant: false,
  },
  {
    id: 5,
    date: 591020225525,
    isImportant: true,
  },
];

And I’m trying to sort this array so elements that are isImportant: true with the most recent date are displayed first and then elements that have isImportant:false with the most recent date

Answer

array.sort(function(a,b){
    if(a.isImportant && !b.isImportant)
        return -1;
    if(!a.isImportant && b.isImportant)
        return 1;
    return b.date-a.date;
});

I hope this will resolve your issue



Source: stackoverflow