Sorting array of date objects javascript error

I am getting weird error, cannot figure it out. I have an array of date objects (AngularJS) and I want to sort them. I am doing as below

console.log(tempDates);
tempDates.sort( function(a, b) {
    return a-b;
});
console.log(tempDates);

      

The problem is changing the tempDates array i.e. date values ​​change. Wrong sorting function? / What am I missing?

original tempDates -

["Jun 19", "Jun 26", "Jul  3", "Jul 10", "Jul 17", "Jul 24", "Jul 31", "Aug  7", "Aug 14", "Aug 21", "Aug 28", "Sep  4", "Sep 11"]

      

after sorting,

["Jun 19", "Jun 26", "Jul  1", "Jul  3", "Jul 10", "Jul 17", "Jul 24", "Aug  7", "Aug 14", "Aug 21", "Aug 28", "Sep  4", "Sep 11"]

      

(Note that the array consists of DATE objects, the console output I put in is just readable)

The dates change as "Jul 1" appears out of nowhere and "Jul 31" is removed from the list. Any reason why this is happening?

+3


source to share


1 answer


You are sorting date objects, not numbers. To sort them as numbers, you will need to do something like this:

console.log(tempDates);
tempDates.sort( function(a, b) {
    return a.getTime() - b.getTime(); 
});
console.log(tempDates);

      



.getTime () converts the string representation of a date to an actual number. (Milliseconds since 1970/01/01)

0


source







All Articles