假设我们有一个像这样的字符串日期数组-
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" ];
我们需要编写一个包含一个这样的数组的JavaScript函数。该函数应该从该数组中找到最早和最新的日期。
然后,该函数最终应返回一个包含这两个日期的对象。
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));
输出结果
控制台中的输出将是-
{ min: '2017-01-22 00:21:17.0', max: '2017-01-27 11:35:43.0' }