I need a way in Javascript to sort strings as in Windows but it seems it's impossible.
Windows explorer sorts like this:
1.jpg - 2.jpg - 3.jpg - ....
While Javascript sorts like this:
1.jpg - 10.jpg - 11.jpg - 2.jpg -...
Windows sorts based on the numeral value in the filename while Javascript just sorts by a characters' ASCII code.
Sometimes filenames aren't just numbers or text but a combination of both, eG:
"mark 01 in school.jpg"
"mark 02 in school.jpg"
"john 05 in theater.jpg"
What I need is a Javascript function that sorts like shown above.
My question is: is there a function in JS or how can I implement one on my own?
You can try the following algorithm for your sorting. It sorts based on characters.
You will have to write your own sort function and pass it as argument to sort method. Simple example:
your_array.sort(sortfunction)
function sortfunction(a, b){
var num1 = extractNumberFrom(a);
var num2 = extractNumberFrom(b);
return num1 - num2;
}
Just create a sort callback that sorts on strings first, then checks for numbers and sorts those correctly as well, something like
var arr = [ "test2.jpg", "test10.jpg", "test1.jpg", "test11.jpg" ] arr.sort(function(a,b) { for (var i = 0; i < a.length; i++) { var _a = a.charAt(i), _b = b.charAt(i), _c = _a.localeCompare(_b); if ( _c != 0 ) return isNaN(_a) || isNaN(_b) ? a.localeCompare(b) : _a - _b; } }); document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>';
I created a flexibleSort
function that first checks whether all your filename in an array has number only or not. If it has number only then it will compare it as Integer/number, otherwise it will treat it as String.
var arr_number = ["2.jpg", "1.jpg", "3.jpg"]; var arr_string = ["mark 01 in school.jpg","mark 02 in school.jpg","john 05 in theater.jpg"]; var arr_number_1 = ["1.jpg","10.jpg","11.jpg","2.jpg"]; flexibleSort(arr_number); flexibleSort(arr_string); flexibleSort(arr_number_1); function flexibleSort(obj){ var all_number = true; $.each(obj, function(index, value){ if(!$.isNumeric(value.split(".")[0])){ all_number = false; } }); if(all_number === true){ obj.sort(function(a, b){return parseInt(a.split(".")[0])-parseInt(b.split(".")[0])}); }else{ obj.sort(function(a, b){return a > b}); } $.each(obj, function(index, value){ $('#result').append("<p>"+value+"</p>"); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="result"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.