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

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

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 Denunciar

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