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

164
Views
Loop through array of Date Objects and compare which one is latest and earliest

If I have this structure:

 const datesList = [2022-07-15T19:41:12.620Z, 2022-07-20T11:21:52.596Z, 2022-07-13T11:21:50.596Z]

How can I loop through it and find out which one is the later and the earlier date?

I've tried using forEach loop and its not working..

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can compare using getTime() which gets the time in ms since 1970

var dateList = [new Date(Date.parse("2022-07-15T19:41:12.620Z")), new Date(), new Date(+5), new Date(1236876666273)]

console.log(dateList.sort(function(a, b) {
  if (a.getTime() < b.getTime()) {
    return -1
  }
  if (a.getTime() > b.getTime()) {
    return 1
  }
  return 0
}))

about 4 years ago · Santiago Trujillo Report

0

  • Date.parse() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC of string input for valie date.
  • I just used dort function of es6.

const datesList = ["2022-07-15T19:41:12.620Z", "2022-07-20T11:21:52.596Z", "2022-07-13T11:21:50.596Z"];
console.log(datesList.sort((a, b) => Date.parse(a) - Date.parse(b)));

about 4 years ago · Santiago Trujillo Report

0

  1. Get each string date, abd parse them into timestamp numbers
    .map(d => Date.parse(d))
    
  2. Sort the array of timestamp numbers
    .sort((a, b) => a - b)
    
  3. Convert the numbers into date strings
    .map(t => new Date(t));
    

const dates = ['2022-07-15T19:41:12.620Z', '2022-07-20T11:21:52.596Z', '2022-07-13T11:21:50.596Z'];
 
 let output = dates
 .map(d => Date.parse(d))
 .sort((a, b) => a - b)
 .map(t => new Date(t));
 
console.log(output);

about 4 years ago · Santiago Trujillo 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!