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

162
Vistas
Algorithm to sort an array in javascript

I am having difficulty figuring out a solution.

I have an array similar to this.

// Original array 
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"]; 

// The sorted array needs to be like this. 
sorted_array = ["1", "1A", "01A", "2", "02B", "03B", "10"]; 

I have tried writing a custom sort function like this but I am unable to find a solution. I appreciate any help.

 const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];

 const sorted_array = orig_array.sort((a, b) => {
  if (a - b) {
   return a - b;
  }
 if (a.localeCompare(b) === -1) {
  return a.length - b.length;
 } else {
 return 1;
}
});
console.log(sorted_array);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can first apply parseInt to both strings to get the first numeric parts and subtract them. If the numeric parts are equal, then subtract the lengths.

const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"]; 
console.log(orig_array.sort((a,b)=>parseInt(a)-parseInt(b)||a.length-b.length));

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