Home > Software engineering >  Javascript - Sort date range array function
Javascript - Sort date range array function

Time:01-31

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.

CodePudding user response:

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)

CodePudding user response:

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);

  •  Tags:  
  • Related