How To Sort An Array Of Objects Using Their Object Properties
Solution 1:
If your array is arr:
arr.sort(function(a,b) {
return ( a.date < b.date ? -1 : (a.date > b.date ? 1 : 0 ) );
});
Solution 2:
You need to pass your own function to .sort()
, something like this:
someArray.sort(function(a, b) {
if (a.date < b.date)
return -1;
else if (a.date > b.date)
return 1;
return 0;
});
Your function just needs to be able to compare any two given objects and return negative or positive depending on which comes first or zero if they're equal. The .sort()
function will take care of the rest.
This means you can sort on whatever property of the object you like, and even (optionally) introduce a secondary sort for cases where the first property is equal. You can also control ascending versus descending just by negating your return values.
Solution 3:
You can supply a sort function to the Array's sort method:
// Sample data
var newsArray = [
{date: '2010/8/12'},
{date: '2012/8/10'},
{date: '2011/8/19'}
];
// Sorting function
function sortNewsArray(arr) {
return arr.sort(function(a, b) {
return new Date(a.date) - new Date(b.date);
}
);
}
Provided the date strings can be converted to dates that simply. If not, just reformat so that they can, either in the data or the sort function.
Original order:
- 2010/8/12
- 2012/8/10
- 2011/8/19
Sorted order:
- 2010/8/12
- 2011/8/19
- 2012/8/10
Post a Comment for "How To Sort An Array Of Objects Using Their Object Properties"