I know this must be relatively simple, but I have a dataset of JSON that I would like to sort by date. So far, I've run into problems at every turn.
Right now I have the date stored as this.lastUpdated
.
I have access to jquery if that helps, but I realize the .sort() is native JS.
Thanks in advance.
Asked
Active
Viewed 6.7k times
31

Munzilla
- 3,805
- 5
- 31
- 35
-
What format is your date field? – orolo Oct 04 '10 at 21:26
-
2look here similar question http://stackoverflow.com/questions/979256/how-to-sort-a-json-array – Aaron Saunders Oct 04 '10 at 21:27
-
JSON is a serialized format (a string). I don't think you can do anything to it until you convert it to an object (eval or custom js framework function). – Alin Purcaru Oct 04 '10 at 21:29
1 Answers
68
Assuming that you have an array of javascript objects, just use a custom sort function:
function custom_sort(a, b) {
return new Date(a.lastUpdated).getTime() - new Date(b.lastUpdated).getTime();
}
var your_array = [
{lastUpdated: "2010/01/01"},
{lastUpdated: "2009/01/01"},
{lastUpdated: "2010/07/01"}
];
your_array.sort(custom_sort);
The Array sort
method sorts an array using a callback function that is passed pairs of elements in the array.
- If the return value is negative, the first argument (
a
in this case), will precede the second argument (b
) in the sorted array. - If the returned value is zero, their position with respect to each other remains unchanged.
- If the returned value is positive,
b
precedesa
in the sorted array.
You can read more on the sort
method here.

Asad Saeeduddin
- 46,193
- 6
- 90
- 139

Sean Vieira
- 155,703
- 32
- 311
- 293
-
Unserialized JSON is a non-array object. `.sort()` is only available on arrays. – Peter Ajtai Oct 05 '10 at 00:40
-
1Sorry for the downvote! It was an accident. I was not paying attention when I was clicking on the page and now I cannot change it. – Whitecat Nov 23 '17 at 17:42