user3214545
user3214545

Reputation: 2213

Get consecutive dates in pairs from array

I am trying to extract consecutive days pairs from an array. For example:

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

I would like the following output

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

In the above example you can see, if there is more than 2 consecutive days(13, 14, 15), it splits them into pairs of 13 & 14, 14 & 15.

I did get the following example from another question answered

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;
    },
    [[]]
  );
};

But it still doesnt quite give the desired output:

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

Upvotes: 1

Views: 314

Answers (1)

Hamza Arshad
Hamza Arshad

Reputation: 846

You can try the following code:

const test = (arr) => {
    let sorted_arr = arr.sort();
    let result = [[sorted_arr[0]]];
    let j=0;
    for(let i=1; i<arr.length; i++) {
        var date = sorted_arr[i];
        var prev_date = sorted_arr[i-1];

        if(moment.duration(moment(date).diff(moment(prev_date))).days() > 1) {
            j++;
            result.push([date]);
        } else {
            if(result[j].length == 2) {
                 j++;
                 result.push([prev_date, date]);
            } else {
                 result[j].push(date);
            }
        }
     }
     return result;
};

Upvotes: 1

Related Questions