Sorting an Alphanumeric String Descending

I need to sort an array of alphanumeric elements as follows. From:

2 xxx 20 axxx 38 xxxx 20 bx 8540 xxxxxx 

in

 8540 xxxxx 38 xxxx 20 axxx 20 bx 2 xxx 

Thus, sorted in descending order with respect to numbers, then in ascending order in alphabetical order. Numbers are always separated from alphabetic characters (denoted by "xxxx") by a single space, but numbers are of variable length.

I suspect that I need to use some kind of Regex in the sort () function and separate the numbers with a space and then sort it, but I don’t know how to link it in alphabetical order. Any code examples? Thank you very much!

+6
source share
2 answers

There is no need for RegEx because Array.sort() accepts a 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); 
+6
source

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/

+4
source

Source: https://habr.com/ru/post/946916/


All Articles