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!
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.
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;
})
Try like this:
array.sort(function(prev,next){
return prev.order-next.order
})
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
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
Try
Myarray.sort(function(x,y)
{
return x.order-y.order
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.