Reputation: 4812
I have an array like this:
var myarray = [Object { category="21f8b13544364137aa5e67312fc3fe19", order=2}, Object { category="5e6198358e054f8ebf7f2a7ed53d7221", order=8}]
Of course there are more items in my array. And now I try to order it on the second attribute of each object. (the 'order' attribute)
How can I do this the best way in javascript?
Thank you very much!
Upvotes: 3
Views: 72
Reputation: 324
write your own compare function
function compare(a,b) {
if (a.last_nom < b.last_nom)
return -1;
if (a.last_nom > b.last_nom)
return 1;
return 0;
}
objs.sort(compare);
Source: Sort array of objects by string property value in JavaScript
Upvotes: 0
Reputation: 25352
Try like this
//ascending order
myarray.sort(function(a,b){
return a.order-b.order;
})
//descending order
myarray.sort(function(a,b){
return b.order-a.order;
})
Upvotes: 2
Reputation: 10163
You can write your own sort compare function:
myarray.sort(function(a,b) {
return a.order - b.order;
});
The compare function should return a negative, zero, or positive value to sort it up/down in the list.
When the sort method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Upvotes: 3
Reputation: 28445
You can do something like following
myarray.sort(function(a,b){
return a.order-b.order;
})
For reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 2
Reputation: 2857
Try like this:
array.sort(function(prev,next){
return prev.order-next.order
})
Upvotes: 2