Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Grouping dates to nearest

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!