-1

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

Azametzin
  • 5,223
  • 12
  • 28
  • 46
mrcn
  • 3
  • 1
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Jeremy Kahan Feb 14 '20 at 11:30
  • Try to split this into 2 arrays, one for important items one for not, then sort each of them by date, then join them into single sorted array. – kuklyy Feb 14 '20 at 11:30
  • Does this answer your question? [Javascript sort function. Sort by First then by Second](https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second) – Pedro Lima Feb 14 '20 at 11:31

2 Answers2

0
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

Raman Dhoot
  • 115
  • 4
0
array.sort((a,b)=>{
    if(a.isImportant==b.isImportant){
        return b.date-a.date;
    }else{
        return a.isImportant?-1:1;
    }
})

duplicate of this

Ravi Sevta
  • 2,817
  • 21
  • 37