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

192
Vistas
How to parse numbers in strings and sort them?

I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

const array = ["test 3","test 1","some test","another test","test 2"];

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You need to get a numerical value from the string or a large value to sort strings without any digit to the bottom. then sort by string.

const
    getDigits = s => (s.match(/\d+/) || [Number.MAX_VALUE])[0],
    array = ["test 3", "test 1", "some test", "another test", "test 2"];

array.sort((a, b) =>
    getDigits(a) - getDigits(b) ||
    a.localeCompare(b)
);

console.log(array);

about 4 years ago · Juan Pablo Isaza Denunciar

0

const array = ["test 3","test 1","some test","another test","test 2"];
array.sort(function(a, b) {
    let aNumber = a.replace( /^\D+/g, '');
    let bNumber = b.replace( /^\D+/g, '');
    if (aNumber.length * bNumber.length) {
        a = parseInt(aNumber);
        b = parseInt(bNumber);
    } else if (aNumber.length + bNumber.length) {
        return aNumber.length ? -1 : 1;
    }
    return ((a === b) ? 0 : ((a > b) ? 1 : -1));
})
console.log(array);

So, you have three main cases

  • 1: Both items contain numbers. In this case you need to extract the numbers from both and compare them
  • 2: Exactly 1 item contains numbers. In this case it will precede the other value
  • 3: None of the items contain numbers. In this case we compare the items as they are
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use this function :

array.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
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