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

425
Visualizações
How JS sorting the numbers?

I'm learning Javascript and I faced a problem with sorting numbers I don't understand how work sorting function and I find an other way to sort the numbers but it was with list not with arrays I need explanations. I also see this link : Sorting array with numbers without sort() method

const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b) {
  return a - b
});
document.getElementById("demo2").innerHTML = points;

document.getElementById("demo3").innerHTML = points.sort();
unsorted:
<div id="demo1"></div>
sorted:
<div id="demo2"></div>
sorted alphabetically:
<div id="demo3"></div>

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

0

const points = [40, 100, 1, 5, 25, 10];

console.log(points)

console.log(points.sort())

console.log(points.sort(function(a, b){return (a - b);}))

By default, the sort() function sorts values as strings.

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect results when sorting numbers.

You can fix this by providing a compare function:

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

Solution

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