Im new to Javascript and I'm looking for a way to order an array of dates (newest to oldest). I was going to right up my own function, but wanted to check if there was a built-in way or better way to do it in Javascript.
Asked
Active
Viewed 3,363 times
0
-
There is no better way than using `sort` and writing your comparison function. – kapa May 12 '14 at 09:21
2 Answers
1
Use the Array.sort()
method and pass it a function which compares the getTime()
value of the dates.

kapa
- 77,694
- 21
- 158
- 175
0
I think you can use the Date
object, and with the function UTC()
or getTime()
you will get a value which can be sorted easily and transferred back to a Date
object. Store the Date's in an array and use Array.sort()
and first define your sort function:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Source: www.w3schools.com/jsref/jsref_sort.asp
So something like:
var dates = [...some dates...];
dates.sort(function(a, b){return a.getTime() - b.getTime()});
Edit: since UTC()
gives a string
and getTime()
an int
, getTime()
would be better.

martijnn2008
- 3,552
- 5
- 30
- 40