I need to sort an array of alphanumerical items as follows. From:
2 xxx
20 axxx
38 xxxx
20 bx
8540 xxxxxx
to:
8540 xxxxx
38 xxxx
20 axxx
20 bx
2 xxx
Thus, sorted descending with respect to the numbers, then ascending alphabetically. The numbers are always separated from the alphabetical characters (denoted "xxxx") by a single space, but the numbers are variable length.
I suspect I need to use some Regex in the sort() function and splitting off the numbers by the space then sorting it, but I don't know how to tie in the alphabetical sorting. Any code samples? Thanks so much!
No need for RegEx, because Array.sort()
accepts custom function:
http://jsfiddle.net/EFGK9/
var arr=["2 xxx","20 axxx","38 xxxx","20 bx","8540 xxxxxx"];
arr.sort(function(a,b){
a=a.split(" ");
b=b.split(" ");
var an=parseInt(a[0],10);
var bn=parseInt(b[0],10);
return an<bn?1:(an>bn?-1:(a[1]<b[1]?-1:(a[1]>b[1]?1:0)));
});
console.log(arr);
Something like this will work:
var arr = [
"2 xxx",
"20 axxx",
"38 xxxx",
"20 bx",
"8540 xxxxxx"
];
arr.sort(function(a, b) {
var aParts = a.split(" "),
bParts = b.split(" "),
aNum = +aParts[0], // convert numeric parts
bNum = +bParts[0]; // to actual numbers
if (aNum > bNum)
return -1;
else if (aNum < bNum)
return 1;
else
return aParts[1].localeCompare(bParts[1]);
});
Demo: http://jsfiddle.net/KLa2J/
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