简体   繁体   中英

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);
  

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM