bala3569
bala3569

Reputation: 11010

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.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

Upvotes: 1

Views: 5792

Answers (3)

Sunny Nirala
Sunny Nirala

Reputation: 9

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

Upvotes: 0

Mitch Satchwell
Mitch Satchwell

Reputation: 4830

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.

Upvotes: 1

Julien Lafont
Julien Lafont

Reputation: 7877

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

Upvotes: 2

Related Questions