3

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!

progNewbie
  • 4,362
  • 9
  • 48
  • 107
  • You can pass a function(){} to the sort function on array. Write your own function and it will be done. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Superdrac Sep 17 '15 at 07:35

6 Answers6

3

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.

Mark Knol
  • 9,663
  • 3
  • 29
  • 44
2

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;
})

JSFIDDLE

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
2

Try like this:

array.sort(function(prev,next){
   return prev.order-next.order
 })
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
2

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

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

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

Community
  • 1
  • 1
user9480
  • 324
  • 1
  • 13
0

Try

Myarray.sort(function(x,y)
{
   return x.order-y.order
})
user786
  • 3,902
  • 4
  • 40
  • 72