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

247
Vistas
I use this function to order a nested array in JavaScript but im failing to order numerical values

I use this function to order nested arrays of objects (JSON) in Javascript (English isnt my native lang)

 nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
    const a = prop2 ? e1[prop1][prop2] : e1[prop1],
        b = prop2 ? e2[prop1][prop2] : e2[prop1],
        sortOrder = direction === "asc" ? 1 : -1
    return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
}

previously i cleaned all the null values of the array with this function

array = JSON.parse(JSON.stringify(array), (key, value) => value === null ? '' : value);

the trouble im having is that is only ordering string values and date values, the numerical values are treated like strings, i need some advice on what can i add to the nestedSort function to work dinamically ordering : strings, dates, and numerical values?

i call the function with this code

objJson = objJson.sort(nestedSort(value, null, records_order));

[Solved] Idk if it was the best way, i will appreciate if someone has a better way to do it

 nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
    const a = prop2 ? e1[prop1][prop2] : e1[prop1],
        b = prop2 ? e2[prop1][prop2] : e2[prop1],
        sortOrder = direction === "asc" ? 1 : -1
        if (isNaN(a) && isNaN(b)){
          return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
        }else{
          return sortOrder == 1 ?  (a - b) : (b - a);
        }
}
about 4 years ago · Santiago Trujillo
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