I got array of objects that is list items
arr = [{id:"1",name:"item1",created:"Wed Feb 04 2015 03:36:42 GMT+0400"},{id:"2",name:"item2",created:"Sat Feb 04 2015 02:44:39 GMT+0400"}]
i want to get the latest created Item any ideas ?
The item with the biggest ID is the latest created item.
function compare(a,b) {
if (a.id < b.id)
return -1;
if (a.id > b.id)
return 1;
return 0;
}
arr.sort(compare);
var latestItem = arr[arr.length - 1];
You can also compare the dates created in the Compare fuction and it will give the same result.
function compare2(a,b) {
var date1 = new Date(a.created);
var date2 = new Date(b.created);
if (date1 < date2)
return -1;
if (date1 > date2)
return 1;
return 0;
}
arr.sort(compare2);
var latestItem = arr[arr.length - 1];