Skip to content Skip to sidebar Skip to footer

How To Sort A Alphanumeric String Value?

Here i am sorting a alphanumeric string value using javascript.But it sorts the string alone.What i need is to split the numeric values from the string and sort the numeric values.

Solution 1:

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

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

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


Solution 2:

If you wish to sort first by the string, and then by the numeric value after the space, you will need to specify your own function to pass in to the sort function, like so:

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 sorts first by the string and then by the numbers after the string (numerically). The above code works on the assumption values being sorted will always be in the above format and lacks any checking on the input.


Solution 3:

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;
}

Post a Comment for "How To Sort A Alphanumeric String Value?"