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

204
Visualizações
Javascript sort mixed alphanumeric array - letters ascending, numbers descending

I have an alphanumeric array that I need to sort by alphabet ascending and then by number descending, the array is a as follows:

[A1, A4, A2, A3, C2, C4, C3, B3, B5, B4]

How do I sort the array using JavaScript, so it looks like:

[A4, A3, A2, A1, B5, B4, B3, C4, C3, C2]

I have tried:

arr.sort() 

but that only sorts it alphabetically and numerically ascending, giving me:

[A1, A2, A3, A4, B3, B4, B5, C2, C3, C4]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you have always a single letter, you could sort by the numerical rest and by the first letter.

const
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => a[0].localeCompare(b[0]) || b.slice(1) - a.slice(1));

console.log(...array);

If you have more than one letter, you could take a regular expression and get only digits and non digits, separated into an object.

const
    getValues = string => ({
        letters: string.match(/\D+/)[0],
        digits: string.match(/\d+/)[0]
    }),
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => {
    const [aa, bb] = [a, b].map(getValues);

    return aa.letters.localeCompare(bb.letters)
        || bb.digits - aa.digits;
});

console.log(...array);

about 4 years ago · Juan Pablo Isaza Relatório

0

array.sort take a callback where you can define the condition on how you compare two elements in your array

to perform your need an idea can be to return the comparison of second character if first one is identical

var data = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];
var result = data.sort((a, b) => {
  if (a === b) {
     return 0;
  }
  if (a[0] === b[0]) {
    return (a[1] > b[1]) ? -1 : 1;
  }
  return (a > b) ? 1 : -1;
});
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