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!

1

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Try like this:

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

Comments

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

Comments

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

Comments

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

Comments

0

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.