在 JavaScript 中根据最小和最大日期对数组进行排序?
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/3 6:36:17
假设我们有一个像这样的字符串日期数组 −
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' }
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

