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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With