猿问

从数组中成对获取连续日期

我正在尝试从数组中提取连续的天数对。例如:


const arr = [ '2017-06-08', '2017-06-09', '2017-08-22','2017-06-13','2017-06-14','2017-06-15','2017-07-15'];

我想要以下输出


[['2017-06-08', '2017-06-09'], ['2017-06-13', '2017-06-14'], ['2017-06-14', '2017-06-15']]

在上面的示例中,您可以看到,如果连续超过 2 天(13、14、15),它将它们分成 13 和 14、14 和 15 对。


我确实从另一个回答的问题中得到了以下示例


const test = (arr) => {

  return arr.reduce(

    (acc, date) => {

      const group = acc[acc.length - 1];

      console.log(group[group.length - 1]);

      if (

        moment(date).diff(moment(group[group.length - 1] || date), 'days') > 1

      ) {

        acc.push([date]);

      } else {

        group.push(date);

      }

      return acc;

    },

    [[]]

  );

};

但它仍然没有给出所需的输出:


[ [ '2017-06-08', '2017-06-09' ],

  [ '2017-08-22', '2017-06-13', '2017-06-14', '2017-06-15' ],

  [ '2017-07-15' ] ]


米琪卡哇伊
浏览 92回答 1
1回答

翻翻过去那场雪

您可以尝试以下代码:const test = (arr) => {&nbsp; &nbsp; let sorted_arr = arr.sort();&nbsp; &nbsp; let result = [[sorted_arr[0]]];&nbsp; &nbsp; let j=0;&nbsp; &nbsp; for(let i=1; i<arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var date = sorted_arr[i];&nbsp; &nbsp; &nbsp; &nbsp; var prev_date = sorted_arr[i-1];&nbsp; &nbsp; &nbsp; &nbsp; if(moment.duration(moment(date).diff(moment(prev_date))).days() > 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push([date]);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(result[j].length == 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result.push([prev_date, date]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result[j].push(date);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return result;};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答