0

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)
seriously
  • 1,202
  • 5
  • 23

2 Answers2

3

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);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

.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);
zer00ne
  • 41,936
  • 6
  • 41
  • 68