Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda