How to sort an array of objects using their object properties
If I have an array of objects with p开发者_JAVA百科roperties and I wanted to sort the objects by a specific property, how would I be able to do this? For example, let's say that I had a bunch of news
objects each with a date
property.
How would I be able to sort each of the objects in javascript by date?
If your array is arr:
arr.sort(function(a,b) {
return ( a.date < b.date ? -1 : (a.date > b.date ? 1 : 0 ) );
});
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.
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
精彩评论