从单个日期数组创建日期范围

时间:2017-11-23 09:29:54

标签: javascript arrays date

如何从一个日期数组中创建日期范围(从最新到最旧)?

我有这个日期数组:

{{1}}

我希望得到以下日期范围:

{{1}}

我想在JavaScript中实现这一目标

4 个答案:

答案 0 :(得分:1)

假设日期是有序的,您可以循环使用for循环到最后一项,并且每对Array#slice

var dates = ["2017-11-16T12:12:50.323Z", "2017-11-15T16:13:24.219Z", "2017-11-14T16:13:55.449Z", "2017-11-13T06:56:21.332Z"];

var ranges = [];
for(var i = 0; i < dates.length - 1; i++) {
  ranges.push(dates.slice(i, i + 2));
}

console.log(ranges);

答案 1 :(得分:0)

您可以使用Array#reduce模式获取数组的实际元素和下一个结果的新项目,该模式将下一个循环的下一个项目作为实际项目返回。

&#13;
&#13;
var data = ["2017-11-16T12:12:50.323Z", "2017-11-15T16:13:24.219Z", "2017-11-14T16:13:55.449Z", "2017-11-13T06:56:21.332Z"],
    result = [];
    
data.sort((a, b) => b > a || -(b < a)); // desc

data.reduce((a, b) => (result.push([a, b]), b));

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var data = ["2017-11-16T12:12:50.323Z", "2017-11-15T16:13:24.219Z", "2017-11-14T16:13:55.449Z", "2017-11-13T06:56:21.332Z"];

var paired = data.sort().slice(0, -1).map(function(d, i) {
  return [d, data[i+1]];
})

console.log(paired);
&#13;
&#13;
&#13;

或者使用es6,您可以在一行中完成:

&#13;
&#13;
let data = ["2017-11-16T12:12:50.323Z", "2017-11-15T16:13:24.219Z", "2017-11-14T16:13:55.449Z", "2017-11-13T06:56:21.332Z"];

let paired = data.sort().slice(0, -1).map((d, i) => [d, data[i+1]])

console.log(paired)
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

由于您不需要任何高级排序,因此您只需使用javascript提供的默认.sort()函数。

var datesSorted = dates.sort();

成对分裂可以在一个循环中完成,因为JavaScript没有提供任何直接的&#34;分裂数组成对#34;功能

最终的脚本应该是这样的:

var dates = ["2017-11-16T12:12:50.323Z", "2017-11-15T16:13:24.219Z", "2017-11-14T16:13:55.449Z", "2017-11-13T06:56:21.332Z"];
var datesSorted = dates.sort();

var datePairs = function(datesSorted) {
    var pairs = [];
    for (var i=0 ; i<datesSorted.length ; i+=2) { //iterate by two
        if (datesSorted[i+1] !== undefined) { //check if a date has a "pair"
            pairs.push ([datesSorted[i], datesSorted[i+1]]); //if it does, push them both
        } else {
            pairs.push ([datesSorted[i]]);
        }
    }
    return pairs;
};

现在,您的日期数组数组应存储在datePairs