var myArray = [{date:"2013.03.01"},{date:"2013.03.08"},{date:"2013.03.19"}];
I tried:
function(a,b){
return b.date > a.date;
}
and
function(a,b){
return b.date - a.date;
}
The console.log in Chrome and Firefox give me the desired output:
"2013.03.19", "2013.03.08", "2013.03.01"
but Safari give the original sorting:
"2013.03.01", "2013.03.08", "2013.03.19"
Why?
To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
Example: Sort an Array in Java in Ascending Order Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.
In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The sort( ) method accepts an optional argument which is a function that compares two elements of the array. If the compare function is omitted, then the sort( ) method will sort the element based on the elements values.
A sort function in JavaScript is supposed to return a real number -- not true or false or a string or date. Whether that number is positive, negative, or zero affects the sort result.
Try this sort function (which will also correctly sort any strings in reverse-alphabetical order):
myArray.sort(function(a,b){
return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
});
"2013.03.01"
is not a date. It's a string.
In order to correctly sort by dates, you need to convert these to dates (timestamps).
var myArray = [{date:"2013.03.01"},{date:"2013.03.08"},{date:"2013.03.19"}];
myArray.sort(function(a,b){
return Date.parse(b.date) - Date.parse(a.date);
});
You might also be able to sort them using direct string comparasions too:
myArray.sort(function(a,b){
return b.date.localeCompare(a.date);
});
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