Skip to content
Advertisement

Sort by Status then by date JavaScript

I have an array of the following type I wan to sort. I want to sort them by the status and show false ones first and and then sort them by their date. I don’t know if I should use group by then sort.

    "itemlist": [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}]

I have used the below code it sorts the array by status but the date sorting is not working. can someone help me with a better method and what am I doing wrong ? , Thanks

var res=itemlist.sort((a, b) => (a.Status === b.Status ) ? 0 : a.Status ? 1 : -1 || b.Date- a.Date);
  

Advertisement

Answer

The reason is that your date is string format,not actually date,you need to change it to date when compare

var res=itemlist.sort(
   (a, b) => (a.Status === b.Status ) ? 
      0 : a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date));

also,you expression is too complex to read and debug,had better to use () to wrap it or use if else condition instead

 var res=itemlist.sort(
   (a, b) => (a.Status === b.Status ) ? 
      0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));

working code

   var itemlist = [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}];
 var res=itemlist.sort(
   (a, b) => (a.Status === b.Status ) ? 
      0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));

//output the sorted result
console.log(res);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement