Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda