Issue
Date b/w 26 April 2020 to 30 April 2020 is not sorting properly weird ahh okay..
1) I am having a array like
[
{
"dateAndTime": "05/05/2020 09:00:00"
},
{
"dateAndTime": "26/04/2020 09:00:00"
},
{
"dateAndTime": "25/05/2020 09:00:00"
}
]
2) Sorting code
this.myArray.sort((a: MyDateClass ,b: MyDateClass) => (b.dateAndTime <= a.dateAndTime ? -1 : 1) );
3) export class
export class MyDateClass {
public dateAndTime: Date;
}
4) Expected output
25/05/2020 09:00:00
05/05/2020 09:00:00
26/04/2020 09:00:00
5) Getting output
26/04/2020 09:00:00
05/05/2020 09:00:00
05/05/2020 09:00:00
Some extra cases if I include array date 28,29,26,27,30 April it will sorting right like 26,27,28,29,30
What is wrong with specific range of date b/w 26 to 30 April ?
Note: This is Ionic 3 and this issue tested in safari, Firefox, Chrome
Updating I also try below mention possible solution but latest time not sorting.
let data=[ { "dateAndTime": "05/04/2020 09:00:00" }, { "dateAndTime": "05/04/2020 09:10:00" }, { "dateAndTime": "05/04/2020 09:09:22" },{ "dateAndTime": "05/05/2020 09:00:00" }, { "dateAndTime": "05/05/2020 09:09:22" }];
let result = data.sort((a,b) => {
let aa = new Date(a.dateAndTime.slice(0,10).split('/').reverse().join('/'));
let bb = new Date(b.dateAndTime.slice(0,10).split('/').reverse().join('/'));
return (bb <= aa ? -1 : 1);
// return (aa <= bb ? 1 : -1);
});
console.log('Sorted___', result);
Output
0: Object { dateAndTime: "05/05/2020 09:00:00" }
1: Object { dateAndTime: "05/05/2020 09:09:22" } //This will be come at place of object 0:first
2: Object { dateAndTime: "05/04/2020 09:00:00" }
3: Object { dateAndTime: "05/04/2020 09:10:00" } // here this will be come at place of object 2:
4: Object { dateAndTime: "05/04/2020 09:09:22" }
Solution
Seems this is due to invalid date
var data=[{ "dateAndTime": "05/04/2020 09:00:00" },{ "dateAndTime": "05/04/2020 09:10:00" },{ "dateAndTime": "05/04/2020 09:09:22" }, { "dateAndTime": "05/05/2020 09:00:00" }, { "dateAndTime": "05/05/2020 09:09:22" }];
result = data.sort((a,b)=>{
aa = new Date(a.dateAndTime.slice(0,10).split('/').reverse().join('/') + a.dateAndTime.slice(10));
bb = new Date(b.dateAndTime.slice(0,10).split('/').reverse().join('/') + b.dateAndTime.slice(10));
return bb - aa;
});
console.log(result);
Answered By - Rajan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.