I use angularjs in project.
I get array of objects from the server. Each object contains few properties and one of them is date property.
Here is the Array
A clean way to do it would be to convert each date to a Date()
and take the max
ES6:
new Date(Math.max(...a.map(e => new Date(e.MeasureDate))));
JS:
new Date(Math.max.apply(null, a.map(function(e) {
return new Date(e.MeasureDate);
})));
where a
is the array of objects.
What this does is map each of the objects in the array to a date created with the value of MeasureDate
. This mapped array is then applied to the Math.max
function to get the latest date and the result is converted to a date.
By mapping the string dates to JS Date objects, you end up using a solution like Min/Max of dates in an array?
--
A less clean solution would be to simply map the objects to the value of MeasureDate
and sort the array of strings. This only works because of the particular date format you are using.
a.map(function(e) { return e.MeasureDate; }).sort().reverse()[0]
If performance is a concern, you may want to reduce
the array to get the maximum instead of using sort
and reverse
.
Also further to @TravisHeeter's answer..
Instead of using 'filter' and grabbing the array index of [0], you can use the .find() method instead as follows:
....
const mostRecentObject = a.find( e => {
const d = new Date( e.MeasureDate );
return d.getTime() == mostRecentDate.getTime();
});
This also makes the code more performant, as it will stop looking after it has found the result, rather than filter which will iterate over all objects in the array.
Modification to Anton Harald's answer: The array I have uses ModDate instead of MeasureDate. I am choosing the most recent date. This works.
getLatestDate(xs) {
if (xs.length) {
return xs.reduce((m,v,i) => (v.ModDate > m.ModDate) && i ? v : m).ModDate;
}
}
m = accumulator, v = current , i = index
Environment: TypeScript, ES6