Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort JSON by date

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.

like image 257
Munzilla Avatar asked Oct 04 '10 21:10

Munzilla


People also ask

How do you sort an array by date in JSON?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

How do I sort items in JSON?

Example-1: Sort JSON object using json. dumps() The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects. Create a python file with the following script sort the JSON objects using json. dumps() function.

How do I sort a JSON key?

Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.


1 Answers

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 precedes a in the sorted array.

You can read more on the sort method here.

like image 145
Sean Vieira Avatar answered Oct 03 '22 13:10

Sean Vieira