Reputation: 2055
moment.js
and loadash.js
const startTime = [ '2021-09-30T02:38:56', '2021-09-30T02:39:56', '2021-09-30T02:40:56', '2021-09-30T02:10:56', '2021-09-30T02:11:56' ]
First 3 dates are same with 1 minute difference, second two dates are same with 1 minute difference.
I wanted to group the dates which are just 5 minutes difference, like below.
[
[ 2021-09-30T02:38:56', '2021-09-30T02:39:56', '2021-09-30T02:40:56' ],
[ '2021-09-30T02:10:56', '2021-09-30T02:11:56' ]
]
I able to achieve the result with multiple array iterations, but is there any pretty way?
Upvotes: 1
Views: 34
Reputation: 3713
Here is a suggestion with a single array iteration if that is pretty way for you:
const startTime = ['2021-09-30T02:38:56', '2021-09-30T02:39:56', '2021-09-30T02:40:56', '2021-09-30T02:10:56', '2021-09-30T02:11:56'];
axisSTime = moment(startTime[1]);
const groupedSTimes = [];
let groupedSTime = [startTime[1]];
const MAX_DIFF_MIN = 5;
startTime.slice(1).forEach((sTime, i, slicedArray) => {
const diffMin = Math.abs(moment(sTime).diff(axisSTime) / 60000);
if (diffMin > MAX_DIFF_MIN) {
groupedSTimes.push(groupedSTime);
groupedSTime = [];
axisSTime = moment(sTime);
}
groupedSTime.push(sTime);
if(i == slicedArray.length - 1) {
groupedSTimes.push(groupedSTime);
}
});
console.log(groupedSTimes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Upvotes: 1