Suppose, we have an array of string dates like this −
const arr = [ "2017-01-22 00:21:17.0", "2017-01-27 11:30:23.0", "2017-01-24 15:53:21.0", "2017-01-27 11:34:18.0", "2017-01-26 16:55:48.0", "2017-01-22 11:57:12.0", "2017-01-27 11:35:43.0" ];
We are required to write a JavaScript function that takes in one such array. The function should find the oldest and the newest date from this array.
And then the function should finally return an object containing those two dates.
Example
const arr = [ "2017-01-22 00:21:17.0", "2017-01-27 11:30:23.0", "2017-01-24 15:53:21.0", "2017-01-27 11:34:18.0", "2017-01-26 16:55:48.0", "2017-01-22 11:57:12.0", "2017-01-27 11:35:43.0" ]; const findMinMaxDate = (arr = []) => { const res = arr.reduce((acc, val, ind) => { if (!ind) { return { min: val, max: val}; }; if (val < acc.min) { acc.min = val; }; if (val > acc.max) { acc.max = val; }; return acc; }, undefined); return res; }; console.log(findMinMaxDate(arr));
Output
And the output in the console will be −
{ min: '2017-01-22 00:21:17.0', max: '2017-01-27 11:35:43.0' }