I have an array of objects with several key value pairs, and I need to sort them based on 'updated_at':
[
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
]
What's the most efficient way to do so?
You can create a closure and pass it that way here is my example working
As This answer's states, you can use
Array.sort
.arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})
With this we can pass a key function to use for the sorting
Then for example if we have
We can do
or
or
Sorting by an ISO formatted date can be expensive, unless you limit the clients to the latest and best browsers, which can create the correct timestamp by Date-parsing the string.
If you are sure of your input, and you know it will always be yyyy-mm-ddThh:mm:ss and GMT (Z) you can extract the digits from each member and compare them like integers
If the date could be formatted differently, you may need to add something for iso challenged folks:
Here's a slightly modified version of @David Brainer-Bankers answer that sorts alphabetically by string, or numerically by number, and ensures that words beginning with Capital letters don't sort above words starting with a lower case letter (e.g "apple,Early" would be displayed in that order).
Just another, more mathematical, way of doing the same thing but shorter:
or in the slick lambda arrow style:
This method can be done with any numeric input