Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can javascript sort strings containing numbers?

I'm making a little web-app in which I used AHK and javascript. I make AHK a group of images paths to the .js file something like this

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
 "file:///F:/image2.jpg",
]

and these images should be viewed in the browser the problem is that the sorting method of the two languages is not like the windows sorting.

What I want is javascript sort the file in the variable so that they are like they are viewed in windows like this

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image2.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
]

BTW : I've searched for the functions posted before but it only works with number only and strings containing number like this case

like image 684
Oragon Avatar asked Mar 21 '15 07:03

Oragon


2 Answers

var importedFiles = [
 "file:///F:/image1.jpg",
 "file:///F:/image10.jpg",
 "file:///F:/image11.jpg",
 "file:///F:/image2.jpg",
]

var customSort = function (a, b) {
    return (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g)[0])));

}

// use sort() and apply the customSort function
console.log(importedFiles.sort(customSort));

//outputs

[
   "file:///F:/image1.jpg", 
   "file:///F:/image2.jpg", 
   "file:///F:/image10.jpg", 
   "file:///F:/image11.jpg"
]

DEMO

like image 99
mohamedrias Avatar answered Nov 05 '22 17:11

mohamedrias


You can use a regex to get the number in the filename (assuming your filenames have a pattern to it like the example you have given at the top) and sort it according to it.

var r = /[A-Za-z\:\/]+([0-9]+)\.jpg/;
importedFiles.sort(function(f1, f2) {
     var match1 = r.exec(f1);
     var num1 = match1[1];

     var match2 = r.exec(f2);
     var num2 = match2[1];

     //now you have the two numbers in num1 and num2
     return parseInt(num1, 10) - parseInt(num2, 10);
});

importedFiles will now contain the sorted array as you mentioned.

like image 20
Rahul Nanwani Avatar answered Nov 05 '22 18:11

Rahul Nanwani