Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  '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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading