Artyom Ionash
Artyom Ionash

Reputation: 448

How to aggregate arrays of days weekly in JS?

For example, take the time range from 05/10/2019 to 05/25/2019.

Dates on this interval need to be aggregated like this (2019 is omitted for brevity):

const result = [
  [                                    '05-10', '05-11', '05-12'], // week 1
  ['05-13', '05-14', '05-15', '05-16', '05-17', '05-18', '05-19'], // week 2
  ['05-20', '05-21', '05-22', '05-23', '05-24', '05-25'         ], // week 3
];

What is the best way to solve this problem with JS?
Is it possible to implement this by setting the beginning of the week on any day?
Will packages moment and moment-range help in this?

Upvotes: 0

Views: 724

Answers (2)

ssbarbee
ssbarbee

Reputation: 1712

Here is one possible implementation if you are interested in moment.js code.

But as blex said it's a large lib.

const start = moment('2019-05-10');
const end = moment('2019-05-25');
const array = [[]];
const from_date = moment(start).startOf('isoWeek');
const to_date = moment(end).endOf('isoWeek');

let j = 0;
let added = 0;
for (let currentDate = moment(from_date); currentDate <= to_date; currentDate.add(1, 'day')) {
  if (added === 7) {
    array.push([]);
    j++;
    added = 0;
  }
  if (currentDate.isBetween(start, end, null, '[]')) {
    array[j].push(currentDate.format('MM-DD'));
  }
  else {
    array[j].push('');
  }
  added++;
}
document.getElementById('output').innerText = JSON.stringify(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

<p id="output"></p>

Upvotes: 1

blex
blex

Reputation: 25634

You can go through the dates, and if the day is 1 (Monday), create a new Array in your results:

const startDate = new Date('05-10-2019'),
    endDate = new Date('05-25-2019'),        
    result = [];

function _twoDigits(x) {
  return String(x).padStart(2, '0');
}

let tmp = startDate;
do {
  if (tmp.getDay() === 1 || result.length === 0) {
    // Create a week Array
    result.push([]);
  }
  const str = `${_twoDigits(tmp.getMonth() + 1)}-${_twoDigits(tmp.getDate())}`;
  // Add this date to the last week Array
  result[result.length - 1].push(str);
  // Add 24 hours
  tmp = new Date(tmp.getTime() + 86400000);
} while (tmp.getTime() <= endDate.getTime());

console.log(result);

Note: MomentJS may help, but it's a big library. If you only need to do 2 or 3 basic things with dates, I would recommend not using it. If you need to do a lot of work with dates, then yes, it's a powerful library that will save you a lot of time.

Upvotes: 1

Related Questions