Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  165] [ 7]  / answers: 1 / hits: 42738  / 13 Years ago, thu, september 22, 2011, 12:00:00

If I have a list of object:


var objectList= LIST_OF_OBJECT;

each object in the list contains three attributes: "name", "date","gender"


How to sort the objects in the list by "date" attribute ascending order?


(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")


More From » jquery

 Answers
19

The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:




  • < 0 if the first is less than the second

  • 0 if the first is equal to the second

  • > 0 if the first is greater than the second.



.



objectList.sort(function (a, b) {
var key1 = a.date;
var key2 = b.date;

if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});


You're lucky that, in the date format you've provided, a date that is before another date is also < than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:



objectList.sort(function (a, b) {
var key1 = new Date(a.date);
var key2 = new Date(b.date);

if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});

[#89977] Tuesday, September 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominiqued

Total Points: 189
Total Questions: 122
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;