What is the elegant way to get the latest date from array of objects in client side?
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
.
Return the latest date from array of dates
As per the docs, If at least one of arguments cannot be converted to a
number
, the result isNaN
Andnew Date(NaN)
will beInvalid Date
Wrap the date string in new Date
while pushing in array. When DateObject
is passed through Number
, numeric value representing date
will be returned.
var data = { "reviews": [{ "notes": "Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!", "date": "2015-04-18", "rating": { "overall": 100 } }, { "notes": "I messed up the days I was supposed to be there but they did everything they could to get me a room, which I did. The guy at the front was super nice and then drew me an entire map based off of how much time I had there in Rome. It was extremely helpful and the restaurant he recommends (a friends who you get 10% off of) had good lasagna. Great place for a really reasonable price. Also, the doors do not automatically lock for you room, so just remember to lock your door when you leave. ", "date": "2016-04-18", "rating": { "overall": 94 } }]};
function highestReview() { var maxNumb = []; for (var y = 0; y < data.reviews.length; y++) { maxNumb.push(new Date(data.reviews[y].date)); } var latestDate = new Date(Math.max.apply(null, maxNumb)); console.log(latestDate);}highestReview();
Get object from array that contains the latest date
You could reduce the array and pick the latest date with a single loop approach.
var array = [{ id: 1, date: '2019-01-01' }, { id: 2, date: '2018-01-01' }, { id: 1, date: '2017-01-01' }], result = array.reduce((a, b) => a.date > b.date ? a : b);
console.log(result);
Javascript - get 1 oldest date from array of dates
You want to return a number, not a Boolean (so use -
not >
):
var creationDate = ['Wed Feb 13 21:14:55 GMT 2019', 'Wed Feb 13 21:19:42 GMT 2019', 'Wed Feb 13 21:28:29 GMT 2019', 'Wed Feb 13 21:31:04 GMT 2019', 'Wed Feb 13 21:33:04 GMT 2019'];var orderedDates = creationDate.sort(function(a, b) { return Date.parse(a) - Date.parse(b);});console.log(orderedDates[0]);
Find max date from a string array of dates using max function of date-fns
Convert each to a Date
object and compare using getTime()
function.
var dates = [ 'Thu Jan 12 2015 00:00:00 GMT+0530 (India Time)', 'Tue Feb 25 2015 00:00:00 GMT+0530 (India Time)', 'Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)']
console.log( dates.sort((a,b)=>new Date(b).getTime() - new Date(a).getTime())[0])
Finding the max date from an array of dates using javascript
Try wrapping document.getElementById('date1').value
in new Date().getTime()
.
Also input type="date"
accepts value as yyyy-mm-dd
; try using .toJSON()
, String.prototype.slice()
to set date properly for #maxdate
as yyyy-mm-dd
from value returned as maxDate
function checkMaxDate() { var dateArray = []; var date1 = dateArray.push(new Date(document.getElementById('date1').value).getTime()); var date2 = dateArray.push(new Date(document.getElementById('date2').value).getTime()); var maxDate = Math.max.apply(Math, dateArray); document.getElementById('maxdate').value = new Date(maxDate).toJSON().slice(0, 10);}
Date 1:<input type="date" id="date1" />Date 2:<input type="date" id="date2" />Max Date:<input type="date" id="maxdate" /><button type="button" onclick="checkMaxDate()">Check</button>
Related Topics
How Get Total Sum from Input Box Values Using JavaScript
How to Loop Through Json Array and Get Specific Values
How to Find Any Number That Includes a Certain Digit - Like 1323 Includes the Digit "2"
Check If a String Has White Space
How to Hide Div When You Scroll to Bottom and Show It Again When Scroll Up to Top
Import Image from Json Source (Create-React-App)
How to Separate String and Push to React State
React - How to Add Dynamic Key/Value Pair to an Object
How to Display Loading Message When an Iframe Is Loading
Delete Row on Remove Click React
Retrieving Keys from Json Array Key-Value Pair Dynamically - JavaScript
Postman: How to Check Whether the Field Is Returning Null in the Postman Automation
Javascript Check If Values Exist in Array Json
How to Remove Special Character from Json Without Parsing
Pass Input Tag Value to as Href Parameter
How to Read a Properties File in JavaScript from Project Directory
How to Output Date in JavaScript in Iso 8601 Without Milliseconds and With Z