0

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?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • 1
    [Array.prototype.sort documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) - you pass a function that compares pairs of array entries. – Pointy Jul 30 '15 at 00:02

3 Answers3

1

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;
});
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
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');
Andre Pena
  • 56,650
  • 48
  • 196
  • 243
-1

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
})
nril
  • 558
  • 2
  • 7