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

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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