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

120
Visualizações
Outputting same value for two separate sorting functions

Hey doing drills on sorting and I found something that I don't fully understand.

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> b-a);
let sortedLowesttoHighest = numbers.sort((a, b)=> a-b);

console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);

output: 
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

how come this outputs only the last function's value twice even though I assigned them to two separate variable?

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

0

Arrays are passed by reference. So when you assign to your variable a sorted array and then you sort again, the first variable will also be affected. You can use spread operator to avoid this.

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = [...numbers.sort((a, b)=> b-a)];
let sortedLowesttoHighest = [...numbers.sort((a, b)=> a-b)];

console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);

//output: 
//[ 1, 2, 3, 4, 5 ]
//[ 1, 2, 3, 4, 5 ]

about 4 years ago · Juan Pablo Isaza Relatório

0

The comparator function works little different than some traditional languages that you might be used to.

In js, the return value of comparator is -1, 0 and 1. Although in lot of cases you can get away with using - minus operator.

Having said that, you're passing array as reference here which is causing the problem.

Try running this:

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> a - b);
console.log(sortedHighesttoLowest);

let sortedLowesttoHighest = numbers.sort((a, b)=> b - a);
console.log(sortedLowesttoHighest);

Additionally I'd encourage you to go through here as well

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