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

148
Visualizações
Array Sorting Number 1-100, but 100 is showed as 1st index?

I have a problem when I sort a number of array like this:

let number = '72 65 73 78 75 74 90 81 87 65 55 69 72 78 79 91 100 40 67 77 86';
let numberArray = number.split(' ');
let sortedNumber = numberArray.sort().map(Number);

console.log(sortedNumber);

It will return

[100, 40, 55, 65, 65, 67, 69, 72, 72, 73, 74, 75, 77, 78, 78, 79, 81, 86, 87, 90, 91]

Why 100 show in the first index? And how to make it be the last?

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

0

Try this...

let number = '72 65 73 78 75 74 90 81 87 65 55 69 72 78 79 91 100 40 67 77 86';
let numberArray = number.split(' ');
numberArray.sort(function(a, b) {
  return a - b;
});

console.log(numberArray)

It is trying to sort alphabetically... this will sort as a numeric value

about 4 years ago · Juan Pablo Isaza Relatório

0

You can change the algorithm as:

1) convert string to string array

number.split(" ")

2) map over the string array to make it array of numbers

numberArray.map(Number)

3) pass the custom comparator function in the sort method

.sort((a, b) => a - b)

Note: You can make it one-liner as

let sortedNumber = number.split(" ").map(Number).sort((a, b) => a - b);

let number = "72 65 73 78 75 74 90 81 87 65 55 69 72 78 79 91 100 40 67 77 86";
let numberArray = number.split(" ");
let sortedNumber = numberArray.map(Number).sort((a, b) => a - b);

console.log(sortedNumber);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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