Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

link|improve this question

feedback

4 Answers

up vote 3 down vote accepted

Use the Array sort() method

data.sort(function(a, b){
    return a.date - b.date;
});
link|improve this answer
feedback

try this:

data.sort(function(a,b){
   return a.date - b.date; //to reverse b.date-a.date
});
link|improve this answer
feedback

You can use a custom sort function:

function mySort(a,b) {
    return (a.date - b.date);
}
data.sort(mySort);
link|improve this answer
feedback

This solution works with any type of data:

sort_array_by = function(field, reverse, pr){
  reverse = (reverse) ? -1 : 1;
  return function(a,b){
    a = a[field];
    b = b[field];
    if (typeof(pr) != 'undefined'){
      a = pr(a);
      b = pr(b);
    }
    if (a<b) return reverse * -1;
    if (a>b) return reverse * 1;
    return 0;
  }
}

Then, use it like this (reverse sort):

data.sort(sort_array_by('date', true, function(a){
   return new Date(a);
}));

As another example, you can sort it by a property of type "integer":

data.sort(sort_array_by('my_int_property', true, function(a){
   return parseInt(a);
}));
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.