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