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

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

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