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.
JavaScript
x
9
1
"itemlist": [{
2
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
3
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
4
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
5
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
6
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
7
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
8
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}]
9
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
JavaScript
1
3
1
var res=itemlist.sort((a, b) => (a.Status === b.Status ) ? 0 : a.Status ? 1 : -1 || b.Date- a.Date);
2
3
Advertisement
Answer
The reason is that your date is string format,not actually date,you need to change it to date when compare
JavaScript
1
4
1
var res=itemlist.sort(
2
(a, b) => (a.Status === b.Status ) ?
3
0 : a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date));
4
also,you expression is too complex to read and debug,had better to use ()
to wrap it or use if else condition instead
JavaScript
1
4
1
var res=itemlist.sort(
2
(a, b) => (a.Status === b.Status ) ?
3
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
4
working code
JavaScript
1
14
14
1
var itemlist = [{
2
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
3
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
4
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
5
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
6
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
7
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
8
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}];
9
var res=itemlist.sort(
10
(a, b) => (a.Status === b.Status ) ?
11
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
12
13
//output the sorted result
14
console.log(res);