最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - How to combine consecutive dates in javascript? - Stack Overflow

programmeradmin1浏览0评论

I have an array of dates such as :

test = [ '2018-07-18', '2018-07-19', '2018-07-21', '2018-07-23', '2018-07-24', '2018-07-26'];

And I want to return an array of sub arrays of consecutive dates like this:

result = [['2018-07-18', '2018-07-19'], ['2018-07-21'], ['2018-07-23', '2018-07-24'], ['2018-07-26']]

I'm trying to write a snippet code:

const moment = require('moment');
let visited = [];
const alpha = test.reduce((accumlator, current_date, current_index, array) => {
    let start_date = current_date;
    let successive_date = array[current_index + 1];
    visited.push(start_date);
    if(successive_date && moment(successive_date).diff(moment(start_date), 'days') === 1  
        && visited.includes(successive_date) === false) {
        accumlator.concat(start_date);
        accumlator.concat(successive_date);
    }
    if(successive_date && moment(successive_date).diff(moment(start_date), 'days') !== 1  
        && visited.includes(successive_date) === false) {
        accumlator.concat(successive_date);
    }
    return accumlator;
}, []);

console.log('alpha: ', alpha);

The result when using concat was:

alpha: []

I used push() and it returns an array such test:

alpha:  [ '2018-07-18','2018-07-19','2018-07-21','2018-07-23','2018-07-23','2018-07-24''2018-07-26' ]

How can I fix this in order to get the result such as mentioned above?

I have an array of dates such as :

test = [ '2018-07-18', '2018-07-19', '2018-07-21', '2018-07-23', '2018-07-24', '2018-07-26'];

And I want to return an array of sub arrays of consecutive dates like this:

result = [['2018-07-18', '2018-07-19'], ['2018-07-21'], ['2018-07-23', '2018-07-24'], ['2018-07-26']]

I'm trying to write a snippet code:

const moment = require('moment');
let visited = [];
const alpha = test.reduce((accumlator, current_date, current_index, array) => {
    let start_date = current_date;
    let successive_date = array[current_index + 1];
    visited.push(start_date);
    if(successive_date && moment(successive_date).diff(moment(start_date), 'days') === 1  
        && visited.includes(successive_date) === false) {
        accumlator.concat(start_date);
        accumlator.concat(successive_date);
    }
    if(successive_date && moment(successive_date).diff(moment(start_date), 'days') !== 1  
        && visited.includes(successive_date) === false) {
        accumlator.concat(successive_date);
    }
    return accumlator;
}, []);

console.log('alpha: ', alpha);

The result when using concat was:

alpha: []

I used push() and it returns an array such test:

alpha:  [ '2018-07-18','2018-07-19','2018-07-21','2018-07-23','2018-07-23','2018-07-24''2018-07-26' ]

How can I fix this in order to get the result such as mentioned above?

Share Improve this question asked Jul 19, 2018 at 10:16 SlimSlim 6,19714 gold badges53 silver badges95 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You can try with:

test.reduce((acc, date) => {
  const group = acc[acc.length - 1];
  if (moment(date).diff(moment(group[group.length - 1] || date), 'days') > 1) {
    acc.push([date])
  } else {
    group.push(date);
  }
  return acc;
}, [[]])

Output:

[
  [
    "2018-07-18",
    "2018-07-19"
  ],
  [
    "2018-07-21"
  ],
  [
    "2018-07-23",
    "2018-07-24"
  ],
  [
    "2018-07-26"
  ]
]

Th following helps, if the order of the dates in the array is not maintained. For example, '2018-07-18', '2018-07-19', '2018-07-17' are consecutive but scattered at the start and end of the array.

var test = [ '2018-07-18', '2018-07-19', '2018-07-21', '2018-07-23', '2018-07-24', '2018-07-26', '2018-07-17'], dateformat = "YYYY-MM-DD";

var result = test.reduce(function(acc,val){
    var present, date = moment(val,dateformat);
    acc.forEach(function(arr,index){
        if(present) return;
        if(arr.indexOf(date.clone().subtract(1,'day').format(dateformat))>-1 || arr.indexOf(date.clone().add(1,'day').format(dateformat))>-1)
        {
            present = true;
            arr.push(val);
        }
    });
    if(!present) acc.push([val]);
    return acc;
},[]);

console.log(result)
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You can use this function but dates should be in sorted order.

function get_relative_dates(dates){
    var format = 'YYYY-MM-DD';
    var newDate = [];
    dates.forEach(function(date){
        var lastArr, lastDate;
        if(newDate.length){
            lastArr = newDate[newDate.length -1];
            if(!lastArr.length)
                lastArr.push(date);
            else{
                var lastDate = lastArr[lastArr.length -1];
                if(moment(lastDate, format).add(1,'d').format(format) == date)
                    lastArr.push(date);
                else
                    newDate.push([date]);
            }
        }
        else
            newDate.push([date]);
    });
    return newDate;
}
发布评论

评论列表(0)

  1. 暂无评论