I am trying to arrange my array by the last 4 substrings, which are numbers and it's not working correctly. the code is
function sortArray(){
top10.sort(function(a, b){
var ax = a.substr(6, 4);
var bx = b.substr(6, 4);
return bx>ax;
console.log(top10);
});
}
top10 = [];
$.get('user_db_hm.txt', function(myContentFile)
{
top10 = myContentFile.split("\n");
sortArray();
}, 'text');
the console.log is
["dupes - 9 ", "zombi - 8 ", "rofls - 7 ", "kombi - 6 ", "abcdf - 5", "johny - 4 ", "kolio - 22 ", "gosho - 2 ", "rapis - 14 ", "pesho - 1 "]
You need to return the new sorted array produced by sort()
and make sure the substrings are converted to numbers, so you can compare them correctly.
Try this:
function sortArray(){
return top10.sort(function(a, b){
var ax = Number(a.substr(7, 4));
var bx = Number(b.substr(7, 4));
return bx>ax;
});
}
There are two issues with your program,
parseInt
for converting string to Intger substr
returns data as - 22
which is not what you want So, Try this
top10.sort(function(a, b){
var ax = a.substr(7, 4);
var bx = b.substr(7, 4);
ax.trim();
bx.trim();
return parseInt(bx)>parseInt(ax);
});
console.log(top10);
function strNum(v){ return +v.match(/\d+/)||''; }
function sortArray( arr ){
arr.sort(function(a, b){
var ax = strNum(a);
var bx = strNum(b);
return bx>ax;
});
console.log(arr);
}
$.get("user_db_hm.txt", function( data ){
sortArray( data.split("\n") );
}, "text");
logs:
["kolio - 22", "rapis - 14", "dupes - 9", "zombi - 8", "rofls - 7", "kombi - 6", "abcdf - 5", "johny - 4", "gosho - 2", "pesho - 1"]
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.