if I have a list of object:
var objectList= LIST_OF_OBJECT;
each object in the list contains three attributes: \"name<
The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:
.
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;
}
});