Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorted a javascript array of objects by an object property

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?

like image 291
dotty Avatar asked Jun 02 '11 09:06

dotty


People also ask

Can you sort an array of objects in JavaScript?

Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects by number?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.


1 Answers

Use the Array sort() method

data.sort(function(a, b){
    return a.date - b.date;
});
like image 153
Phil Avatar answered Oct 18 '22 16:10

Phil