1

I need to sort the nrArray array:

var nrArray = nrArray.sort();

What the above does is this:

["1", "17", "206", "22", "3", "6"]

I need this:

["1", "3", "6", "17", "22", "206"]

Ciprian
  • 3,066
  • 9
  • 62
  • 98

4 Answers4

6

Pass in a comparison callback and use parseInt like

var arr = ["1", "17", "206", "22", "3", "6"];

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

console.log(arr);

Update

You actually dont need parseInt as a/b will be auto-converted to numbers. This is because you are subtracting and javascript performs the necessary type conversion. However, the same cannot be said for a + b as this is string concatenation.

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
5

It is because by default the sort() method will do a string based comparison

compareFunction
Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

var nrArray = ["22", "17", "8", "206", "1", "3", "6"];

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

console.log(nrArray)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    `sort`, by default, always compares the the string representation of the values, no matter the actual data type. – Felix Kling Jun 19 '15 at 03:39
  • @FelixKling, interestingly, Aruns answer works without `parseInt`. I assume it is because `a/b` are auto converted to perform the substraction. Is this behaviour safe across browsers? – AmmarCSE Jun 19 '15 at 03:44
  • @AmmarCSE: Yes. Subtraction is only defined on numbers, hence the operands will be converted to numbers. – Felix Kling Jun 19 '15 at 03:46
  • @FelixKling, I see. It works for other operands as well.(I just tried `'1'*'3'` in the console). Thanks for the feedback – AmmarCSE Jun 19 '15 at 03:48
  • @AmmarCSE: Yep. JavaScript will always perform type conversion if necessary. It's pretty straightforward for operands that only support a single data type. `+` is trickier, it's defined for both strings and numbers. – Felix Kling Jun 19 '15 at 03:49
2

Applied from SO: Sort Array Elements (string with numbers), natural sort

You need a natural sort. A good generic natural sort providing the comparison to sort that will also work in case the strings also contain letters:

function naturalCompare(a, b) {
    var ax = [], bx = [];

    a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
    b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });

    while(ax.length && bx.length) {
        var an = ax.shift();
        var bn = bx.shift();
        var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
        if(nn) return nn;
    }

    return ax.length - bx.length;
}

var nrArray = nrArray.sort(naturalCompare);
Community
  • 1
  • 1
Jason W
  • 13,026
  • 3
  • 31
  • 62
-1

Yes because your create array of strings not number. [1, 17, 206, 22, 3, 6] should work fine. moreover no need to write

var nrArray = nrArray.sort();

nrArray.sort(); changes the original array itself

shikhar chauhan
  • 431
  • 1
  • 4
  • 9
  • a) It doesn't work with numbers either. b) You make it sound like assigning the return value of `.sort` would not change the original array. Is that what you mean? Because that is wrong as well. – Felix Kling Jun 19 '15 at 03:53
  • Oops... my bad..... var nrArray = [40, 100, 1, 5, 25, 10]; nrArray.sort(function(a, b){return a-b}); should work.. sorry i didn't check before writing – shikhar chauhan Jun 19 '15 at 08:02