I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings. I am not worried about signed or fl
Use this compare function for sorting ..
function compareLists(a,b){
var alist = a.split(/(\d+)/), // split text on change from anything to digit and digit to anything
blist = b.split(/(\d+)/); // split text on change from anything to digit and digit to anything
alist.slice(-1) == '' ? alist.pop() : null; // remove the last element if empty
blist.slice(-1) == '' ? blist.pop() : null; // remove the last element if empty
for (var i = 0, len = alist.length; i < len;i++){
if (alist[i] != blist[i]){ // find the first non-equal part
if (alist[i].match(/\d/)) // if numeric
{
return +alist[i] - +blist[i]; // compare as number
} else {
return alist[i].localeCompare(blist[i]); // compare as string
}
}
}
return true;
}
Syntax
var data = ["a1b3","a10b11","b10b2","a9b2","a1b20","a1c4"];
data.sort( compareLists );
alert(data);
demo at http://jsfiddle.net/h9Rqr/7/