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.
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.
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.
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.
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.
a
in this case), will precede the second argument (b
) in the sorted array. b
precedes a
in the sorted array.You can read more on the sort
method here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With