Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda