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

188
Visualizações
How to sort an alphanumeric array just based on number in javascript?

consider the following array:

['state1035', 'dm5', 'state123', 'county247', 'county2']

sorting this array on basis of number output should be:

['county2' ,'dm5', 'state123', 'county247', 'state1035']
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming the strings will have numbers together and at the end you can use match to extract the number and sort it:

let arr = ['state1035', 'dm5', 'state123', 'county247', 'county2'];
console.log(arr.sort((a,b) => a.match(/\d+$/).pop() - b.match(/\d+$/).pop()));

The match method used within the compare function will return the array of matched sub-strings from the given string. The regex \d+ will match with numbers at the end and we are sorting based on these numbers.

about 4 years ago · Juan Pablo Isaza Relatório

0

Use a regular expression to match against only the numbers in the string, and then sort the strings based on those numbers.

const data = ['state1035', 'dm5', 'bob0Bob', 'state123', 'county247', 'county2'];

const regex = /\d+/;

const result = data.sort((a, b) => {
  return a.match(regex) - b.match(regex);
});

console.log(result);

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