How to sort an alphanumeric string value?

Here I am sorting an alphanumeric string value using javascript. But it only sorts the string. What I need is to separate the numerical values ​​from the string and sort the numerical values. Here is my code

function sortUnorderedList(ul, sortDescending) { if (typeof ul == "string") ul = document.getElementById(ul); var lis = ul.getElementsByTagName("li"); var vals = []; for (var i = 0, l = lis.length; i < l; i++) vals.push(lis[i].innerHTML); vals.sort(); if (sortDescending) vals.reverse(); for (var i = 0, l = lis.length; i < l; i++) lis[i].innerHTML = vals[i]; } 

Any suggestion?

EDIT : current result

 PPG 101 PPG 102 PPG 57 PPG 58 PPG 99 

Expected Result:

 PPG 57 PPG 58 PPG 99 PPG 101 PPG 102 
+1
source share
3 answers

To perform numerical sorting, you must pass the function as an argument when calling the sorting method.

 vals.sort(function(a, b) { return (ab); }); 

See http://www.javascriptkit.com/javatutors/arraysort.shtml for more details.

+2
source

If you want to sort the string first, and then the numeric value after the space, you will need to specify your own function to go to the sort function, for example:

 arr.sort(function(a,b) { a = a.split(' '); b = b.split(' '); if (a[0] == b[0]) { return parseInt(a[1]) - parseInt(b[1]); } return a[0] > b[0]; }); 

The above example is sorted first by string and then by numbers after the string (numerically). The above code works with estimated assumptions that will always be in the above format and will not be checked at the input.

+1
source
 function sort(values) { var y = values.sort(function (a, b) { var x = a.split(' '); var y = a.split(' '); if (parseInt(x[1]) > parseInt(y[1])) { return a > b; } return a < b; }); return y; } 
0
source

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


All Articles