Sort object by value:
test": [{
"position_order": 3,
}, {
"position_order": 1,
}]
How can I sort this so that obviously the position_order 1 comes first in the array of objects?
Sort object by value:
test": [{
"position_order": 3,
}, {
"position_order": 1,
}]
How can I sort this so that obviously the position_order 1 comes first in the array of objects?
Array.Prototype.Sort allows you to specify a comparison function.
test.sort(function(a, b) {
if(a.position_order < b.position_order) {
return -1;
}
if(b.position_order < a.position_order) {
return 1;
}
return 0;
});
You should consider using Underscore, an amazing JS library for manipulating collections, functions and objects. It works both in the client and in the server (Node.js).
That's how you do it with Underscore.
test = [{
"position_order": 3,
}, {
"position_order": 1,
}];
var ordered = _.sortBy(test, 'position_order');
Use the array sort function
var test = [{
"position_order": 3,
}, {
"position_order": 1,
}];
test.sort(function(a,b){
return a.position_order >= b.position_order ? 1 : -1
})