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?
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.
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.
Use the Array sort() method
data.sort(function(a, b){
return a.date - b.date;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With