基本上我有一系列日期:
var array = ["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"];
我需要根据最大和最小日期对此进行排序; 我试过了:
var lowest = _.max(array, function(o){return o.val;});
console.log(lowest);
但是这会返回-Infinity
而_.min会返回Infinity
问候:)
答案 0 :(得分:0)
您可以在没有回调的情况下使用Array#sort
。这按字符串排序,它在索引零处获得最小值,在最后一个索引处获取最大日期。
var array = ["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"];
array.sort();
console.log(array);
console.log('min', array[0]);
console.log('max', array[array.length - 1]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
另一种解决方案可能是使用Array#reduce
。
var array = ["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"],
result = array.reduce(function (r, a, i) {
if (!i) {
return { min: a, max: a};
}
if (a < r.min) {
r.min = a;
}
if (a > r.max) {
r.max = a;
}
return r;
}, undefined);
console.log(result);
答案 1 :(得分:0)
var array = ["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"];
var timeStamped = array.map((item) => new Date(item).getTime());
console.log('Max is ', new Date(Math.max.apply(null,timeStamped)). toUTCString());
console.log('Min is ', new Date(Math.min.apply(null,timeStamped)). toUTCString());