progNewbie
progNewbie

Reputation: 4812

How to sort an array with objects on the second attribute

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

Answers (6)

user786
user786

Reputation: 4364

Try

Myarray.sort(function(x,y)
{
   return x.order-y.order
})

Upvotes: 0

user9480
user9480

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

Anik Islam Abhi
Anik Islam Abhi

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

JSFIDDLE

Upvotes: 2

Mark Knol
Mark Knol

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

Nikhil Aggarwal
Nikhil Aggarwal

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

Indranil Mondal
Indranil Mondal

Reputation: 2857

Try like this:

array.sort(function(prev,next){
   return prev.order-next.order
 })

Upvotes: 2

Related Questions