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.
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.
Further to @Travis Heeter's answer, this returns the object that contains the latest date:
array.reduce((a, b) => (a.MeasureDate > b.MeasureDate ? a : b));
A more robust solution perhaps might be convert the strings into Date objects every time. Could be noticeably slower if dealing with (very) large arrays:
array.reduce((a, b) => {
return new Date(a.MeasureDate) > new Date(b.MeasureDate) ? a : b;
});
javascript - Get the minimum and maximum dates from JSON - Stack Overflow
javascript - Get max and min dates from an array - Stack Overflow
javascript - Finding minimum and maximum date in an complex json array - Stack Overflow
Finding the max date from an array of dates using javascript - Stack Overflow
Code is tested with IE,FF,Chrome and works properly:
var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));
Something like:
var min = dates.reduce(function (a, b) { return a < b ? a : b; });
var max = dates.reduce(function (a, b) { return a > b ? a : b; });
Tested on Chrome 15.0.854.0 dev
var array = [{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}];
var max = null;
var min = null;
for (var i = 0; i < array.length; i++) {
var current = array[i];
if (max === null || current.source > max.source) {
max = current;
}
if (min === null || current.source < min.source) {
min = current;
}
}
document.getElementById('maxResult').innerHTML = max.source;
document.getElementById('minResult').innerHTML = min.source;
Max: <span id="maxResult"></span><br/ >
Min: <span id="minResult"></span>
You could do something like this, provided your date format is "yyyy-MM-dd".
Convert the date string to dateKey. which always follow the ascending order as the dates proceed. 20160101(Jan 1st) is always less than 20161231(Dec 31st).
Keeping that in mind, just convert the dates to dateKey and map dateKeys to the object and just extract the max and min of the dateKeys and return the actual date.
var datesArray = [{
"source": "2016-11-02",
"sourcecount": 38
}, {
"source": "2016-11-10",
"sourcecount": 30
}, {
"source": "2016-11-31",
"sourcecount": 38
}, {
"source": "2016-01-01",
"sourcecount": 30
}];
var newObject = {};
var dates = datesArray.map(function(obj) {
var regEx = new RegExp(/-/g);
//Convert date to dateKey
var dateKey = parseInt(obj.source.replace(regEx, ""), 10)
newObject[dateKey] = obj;
return dateKey;
});
console.log("Max", newObject[Math.max(...dates)].source);
console.log("Min", newObject[Math.min(...dates)].source);
1) Use map to extract the dates:
var dates = data.map(function(x) { return new Date(x[4]); })
2) Use Math.max / Math.min to get the highest / lowest dates:
var latest = new Date(Math.max.apply(null,dates));
var earliest = new Date(Math.min.apply(null,dates));
var data = [
[1, 622, 782, 783, "2015-04-21"],
[2, 622, 782, 783, "2015-04-21"],
[3, 622, 782, 783, "2015-04-22"],
[4, 622, 782, 783, "2015-04-23"],
[5, 622, 782, 783, "2015-04-24"],
[6, 622, 782, 783, "2015-04-28"],
[7, 622, 782, 783, "2015-04-28"],
[8, 622, 782, 783, "2015-04-29"],
[9, 622, 782, 783, "2015-05-04"],
[10, 622, 782, 783, "2015-05-05"]
];
var minIdx = 0, maxIdx = 0;
for(var i = 0; i < data.length; i++) {
if(data[i][4] > data[maxIdx][4]) maxIdx = i;
if(data[i][4] < data[minIdx][4]) minIdx = i;
}
alert('Max: ' + maxIdx + ', ' + data[maxIdx][4]);
alert('Min: ' + minIdx + ', ' + data[minIdx][4]);
There is my solution, this is a bit long, but very easy to understand and edit for any update. I'm sure we can solve it with 4-5 lines, but whatever, it works.
First, define a month array :
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
Like every time you need to search min/max in an array, you need to initialize min and max with the first value :
var max_end_date = data[0].Events[1].Date;
var min_start_date = data[0].Events[0].Date;
And then, split every date for compare year / month for start en end, and you have a result like this :
$.each(data, function(k, v) {
var month_min_start_date = min_start_date.split("-")[0];
var year_min_start_date = min_start_date.split("-")[1];
var current_start_date = v.Events[0].Date;
var month_current_start_date = current_start_date.split("-")[0];
var year_current_start_date = current_start_date.split("-")[1];
if (year_current_start_date < year_min_start_date
|| year_current_start_date == year_min_start_date && month.indexOf(month_current_start_date) < month.indexOf(month_min_start_date)) {
min_start_date = current_start_date;
}
var month_max_end_date = max_end_date.split("-")[0];
var year_max_end_date = max_end_date.split("-")[1];
var current_end_date = v.Events[1].Date;
var month_current_end_date = current_end_date.split("-")[0];
var year_current_end_date = current_end_date.split("-")[1];
if (year_current_end_date > year_max_end_date
|| year_current_end_date == year_max_end_date && month.indexOf(month_current_end_date) > month.indexOf(month_max_end_date)) {
max_end_date = current_end_date;
}
})
You can try it on JSFiddle
Here's another approach using Math
var data=[
{
Title:"Dummy1",
Events:[{
eventName:"StartDate",
Date:"Jan-2014"
},
{
eventName:"EndDate",
Date:"Feb-2015"
}]
},
{
Title:"Dummy2",
Events:[{
eventName:"StartDate",
Date:"Jan-2013"
},
{
eventName:"EndDate",
Date:"Feb-2015"
}]
},
{
Title:"Dummy3",
Events:[{
eventName:"StartDate",
Date:"Feb-2014"
},
{
eventName:"EndDate",
Date:"Mar-2015"
}]
}];
var startDates = [],
endDates = [];
for (i = 0; i < data.length; i++) {
startDates.push(Date.parse(data[i].Events[0].Date));
endDates.push(Date.parse(data[i].Events[1].Date));
}
Array.min = function( array ){
return Math.min.apply( Math, array );
};
Array.max = function( array ){
return Math.max.apply( Math, array );
};
// or use a library like Moment.js to format dates
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var minDate = new Date(Array.min(startDates)),
minDateFormat = months[minDate.getMonth()]+'-'+minDate.getFullYear();
var maxDate = new Date(Array.max(endDates)),
maxDateFormat = months[maxDate.getMonth()]+'-'+maxDate.getFullYear();
console.log(minDateFormat );
console.log(maxDateFormat);
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>
You were close. Try applying the function inside a newDate, and null instead of Math. You should also new Date(pushedArrayElement) to be a Date object, and not push Strings into the date array.
var maxDate= new Date(Math.max.apply(null,dateArray));
Note that there's cause for error because it's not guaranteed that the user input will be a legal date format.
Use Array#sort with custom sort function and get the last(max) and first(min) values.
data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];
var sorted = data.slice() // copy the array for keeping original array with order
// sort by parsing them to date
.sort(function(a, b) {
return new Date(a) - new Date(b);
});
// get the first and last values
console.log(
'max :', sorted.pop(), 'min :', sorted.shift()
);
Or with a simple Array#forEach loop.
data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];
// initially set max and min as first element
var max = data[0],
min = data[0];
// iterate over array values and update min & max
data.forEach(function(v) {
max = new Date(v) > new Date(max)? v: max;
min = new Date(v) < new Date(min)? v: min;
});
console.log('max :', max, 'min :', min);
IMO, you should use new Date(value)
Nothing seems wrong in your code.
The reason of getting Invalid date is you're not converting date into Date object, you need to convert it in JavaScript date by new Date().
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)
var datesNew=["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];
//This will convert your date into Date object
$.each(datesNew, function(key, value){
dates.push(new Date(value));
});
var min = dates.reduce(function (a, b) { return a < b ? a : b; });
var max = dates.reduce(function (a, b) { return a > b ? a : b; });
var datesNew=["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];
var dates=[];
$.each(datesNew, function(key, value){
//Conver date in Date object
dates.push(new Date(value));
});
var min = new Date(Math.min.apply( null, dates));
var max = new Date(Math.max.apply( null, dates));
//var min = dates.reduce(function (a, b) { return a < b ? a : b; });
//var max = dates.reduce(function (a, b) { return a > b ? a : b; });
console.log(new Date(min).toString());
console.log(new Date(max).toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>