Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!