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

111
Visualizações
Array.sort method not working when sorting by property

I have a basic array, that I'm trying to sort by the source property:

const arr = [
    { source: '64', target: '63' },
    { source: '61', target: '64' },
    { source: '114', target: '63' },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

But this leaves the array untouched. What am I doing wrong here?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I think you are over complicating it.

arr.sort((a,b) => a.source - b.source);
about 4 years ago · Juan Pablo Isaza Relatório

0

Convert your strings in the array to numbers.

const arr = [
    { source: 64, target: 63 },
    { source: 61, target: 64 },
    { source: 114, target: 63 },
];

console.log('before', arr);

arr.sort(
    (a, b) => a.source > b.source
        // move element to a lower index
        ? -1
            // move element to a higher index
            : b.source > a.source
            ? 1
        : 0);
        
console.log('after', arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to convert strings to integers, before making comparisons, otherwise non-empty string will coerce to true and you are basically doing true > true inside your sort resolver.

about 4 years ago · Juan Pablo Isaza Relatório
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