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

98
Views
Javascript - Sort date range array function

For example, I have an array (it came with a string values inside):

const array = [
  '11/13/22 – 12/24/22',
  '1/3/21 – 1/16/21',
  '12/31/20 – 1/20/21',
  '1/10/21 – 1/20/21',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18'
]

After sorting it with default function .sort()

I receive:

[
  '1/10/21 – 1/20/21',
  '1/3/21 – 1/16/21',
  '10/31/20 – 12/20/21',
  '11/13/22 – 12/24/22',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18'
]

What is the best approach to sort date ranges array in ASC and DESC, by the start date?

Note: I also tried a solution with dividing the array to a small arrays and then try to sort them, but the result was almost the same.

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

0

const array = [
  '11/13/22 – 12/24/22',
  '1/3/21 – 1/16/21',
  '12/31/20 – 1/20/21',
  '1/10/21 – 1/20/21',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18',
  '12/31/17 – 1/20/18'
]

//ascending
array.sort(function(a,b){
  a = a.split(' – ')[0]; //taking the start date
  b = b.split(' – ')[0]; ////taking the start date
  return new Date(a) - new Date(b);
});

//descending
/**
array.sort(function(a,b){
  a = a.split(' – ')[0];
  b = b.split(' – ')[0];
  return new Date(b) - new Date(a);
});
**/


console.log(array)

about 4 years ago · Juan Pablo Isaza Report

0

Using Array#sort, String#split, and Date:

const arr = [ '11/13/22 – 12/24/22', '1/3/21 – 1/16/21', '12/31/20 – 1/20/21', '1/10/21 – 1/20/21', '12/31/17 – 1/20/18', '12/31/17 – 1/20/18', '12/31/17 – 1/20/18' ];

const getFirstDate = str => {
  const [date1Str] = str.split(' – ');
  const [month, day, year] = date1Str.split('/');
  return new Date(year, month - 1, day);
}
const res = arr.sort((a, b) => getFirstDate(b) - getFirstDate(a));

console.log(res);

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!