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

232
Visualizações
position array elements in ascending order (numbers are found as substrings inside the array elements)

I have an array, I want to position every array element in ascending order but the numbers are found as substrings of the array elements. I sketched the code below to give you an idea of what I am trying to achieve(it works but its ugly). What is the best way to position every element inside an array in ascending order when the numbers are found as substrings inside the array elements. Thanks in advance.

Take a look at my code to better understand my question!

//this works but is uglyyyyy
const myArray = ['test4.js', 'test3.js', 'test1.js', 'test2.js']
let tempArr = []
for (var i = 0; i < myArray.length; i++) {
  tempArr.push(myArray[i].replace('test', '').replace('.js', ''))
}
const sortedTempArr = tempArr.sort()
let sortedArray = []
for (var i = 0; i < sortedTempArr.length; i++) {
  for (var j = 0; j < myArray.length; j++) {
    if (myArray[j].includes(sortedTempArr[i])) {
      sortedArray.push(myArray[j])
    }
  }
}
console.log(sortedArray)

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Yes that was ugly ;)

Sort takes a function

For descending, switch a and b

I am assuming only ONE number in the string. The regex will produce a wrong result if you have test2version1.js for example

//this works and is pretty
const myArray = ['test4.js', 'test3.js', 'test11.js', 'test1.js', 'test.js', 'test2.js']; 
const re = /\D+/g; // anything not a number
const sortedArray = myArray
  .slice(0) // shallow copy
  .sort((a, b) => a.replace(re, "") - b.replace(re, ""));
console.log(sortedArray);

about 4 years ago · Santiago Trujillo Relatório

0

.sort() the .match(/\d+/)[0] number of each string (coerced into a number). The bracket notation ([0]) ensures that only the first match is used and everything else is ignored.

const array = ['test4.js','test11.js', 'test3.js', 'test1.js', 'test2.js'];

let result = array.sort((a, b) => +a.match(/\d+/)[0] - b.match(/\d+/)[0]);

console.log(result);

about 4 years ago · Santiago Trujillo 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