Home > Net >  Get date ranges from array of dates
Get date ranges from array of dates

Time:11-02

I would like to get all date ranges from the array of dates.

For example:

getDates([
           2022-01-01,
           2022-01-02,
           2022-01-03,    
           2022-01-04,          
           2022-01-09,
           2022-01-10,
           2022-01-15
          ])

Would return

[
    {start: 2022-01-01, end: 2022-01-04},
    {start: 2022-01-09, end: 2022-01-10},
    {start: 2022-01-15, end: 2022-01-15}

]

CodePudding user response:

  • Using Array#sort, sort the array of dates
  • Using Array#reduce, iterate over the sorted list while updating a list of ranges.
    • In each iteration, check the days-difference between the current date and the end of the current range. If it's more than one, push a new range, otherwise, update the end of the current range to the current date

const _getDifferenceInDays = (date1, date2) => {
  const difference = date2.getTime() - date1.getTime();
  return difference / (1000 * 3600 * 24);
}

const getDates = (dates = []) => {
  const arr = [...dates].sort((a, b) => new Date(a) - new Date(b));
  const ranges = arr.reduce((ranges, current) => {
    if(ranges.length === 0) { // first-iteration
      ranges.push({ start: current, end: current }); 
    }
    const currentRange = ranges[ranges.length - 1];
    const endDate = new Date(currentRange.end);
    const currentDate = new Date(current);
    if(_getDifferenceInDays(endDate, currentDate) > 1) {
      ranges.push({ start: current, end: current });
    } else {
      currentRange.end = current;
    }
    return ranges;
  }, []);
  return ranges;
}

console.log( getDates(['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-09', '2022-01-10', '2022-01-15']) );

  • Related