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"]

4
  • to use sort() ... and that's what I did. Commented Jun 19, 2015 at 3:35
  • jQuery doesn't provide any functionality to sort collections. Commented Jun 19, 2015 at 3:36
  • looks like you are sorting alphabetically, and your array items are strings, not integers. Convert them to numbers then sort. Commented Jun 19, 2015 at 3:50
  • 1
    @Brino: That alone does not help because JavaScript's default .sort behavior is weird. Commented Jun 19, 2015 at 3:56

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

5 Comments

sort, by default, always compares the the string representation of the values, no matter the actual data type.
@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: Yes. Subtraction is only defined on numbers, hence the operands will be converted to numbers.
@FelixKling, I see. It works for other operands as well.(I just tried '1'*'3' in the console). Thanks for the feedback
@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.
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);

Comments

-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

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.