Reputation: 9804
I have these object :
var obj1 = {
endDateInMs : 125000001
};
var obj2 = {
endDateInMs: 125000000
};
var obj3 = {
endDateInMs: 125000002
};
and an array containing these objects :
var array1 = [obj1, obj2, obj3];
I would like to sort array1 by date of object. I would like to have the more recent first and the oldiest at the end of the array.
I do the following but it does'nt work :
function compare(a,b) {
if (a.endDateInMs < b.endDateInMs) {
return -1;
}
else if (a.endDateInMs > b.endDateInMs) {
return 1;
}
}
var arrayOfHistoryForThisItem = wall_card_array[item];
var newArraySorted = arrayOfHistoryForThisItem.sort(compare);
var lastElement = newArraySorted[0];
Upvotes: 0
Views: 62
Reputation: 524
Using the open source project http://www.jinqJs.com, its easy.
See http://jsfiddle.net/tford/epdy9z2e/
//Use jsJinq.com open source library
var obj1 = {
endDateInMs : 125000001
};
var obj2 = {
endDateInMs: 125000000
};
var obj3 = {
endDateInMs: 125000002
};
var array1Ascending = jinqJs().from(obj1, obj2, obj3).orderBy('endDateInMs').select();
var array1Descending = jinqJs().from(obj1, obj2, obj3).orderBy([{field:'endDateInMs', sort:'desc'}]).select();
document.body.innerHTML = '<pre>' + JSON.stringify(array1Ascending, null, 4) + '</pre>';
document.body.innerHTML += '<pre>' + JSON.stringify(array1Descending, null, 4) + '</pre>';
Upvotes: 0