1

I have an array that looks like the following

const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png']

I wanna sort it in numerical order but just calling sort is a problem because when sorted it will look like this:

['1.jpeg', '10.png', '12.gif', '2.jpeg', '30.png', '4.png']

How can I sort it in a "correct" way so that it looks like this

[ '1.jpeg', '2.jpeg', '4.png', '10.png', '12.gif', '30.png']

2 Answers2

0

We can use the following code:

const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];
function fileToNumber(file) {
    // we get everything before the period and convert it to a number
    return parseInt(file.split(".")[0], 10);
}
// we sort with a custom comparator based on our fileToNumber function
files.sort((a, b) => fileToNumber(a) - fileToNumber(b));
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

function numberPart (str){
 return parseInt(str.split('.')[0])
}

const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];

files.sort( (a,b) => numberPart(a) - numberPart(b))

console.log(files)
Mechanic
  • 5,015
  • 4
  • 15
  • 38