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

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

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 Denunciar

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