Skip to content Skip to sidebar Skip to footer

Javascript Sort() Isn't Working For Arrays Of More Than 10 Objects In Chrome

While using sort() method in Javascript, I'm not able to correctly sort an array of more than 10 objects. This happens only in Google Chrome; with Firefox and IE it works. I have a

Solution 1:

Array.prototype.sort method expects the sort helper method to return three different types of values.

1. Negative number - If the first element is smaller

2. Positive number - If the second element is smaller

3. Zero            - If both the elements are equal

So, your sortPlayers has to be tweaked a little, like this

function sortPlayers(a, b) {
    if (a.number === b.number) {
        return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
    } else {
        return a.number > b.number ? 1 : -1;
    }
}

Since a.number and b.number are actually integers, you can straight away write like this

return a.number - b.number;

Solution 2:

The sort callback function needs to return negative, 0 or positive number. You are returning a boolean in some cases which can yield inconsistent results and does not match the specification. A simple subtraction of two comparison numbers yields the proper negative, 0 or positive result that the comparison function needs:

functionsortPlayers(a, b) {
    var result = a.number - b.number;
    if (result !== 0) {
        return result;
    }
    return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
}

Working demo: http://jsfiddle.net/jfriend00/Q6Qa2/

In addition, there is no need to use parseInt() on things that are already numbers. And, if you did use parseInt(), you MUST pass the radix value (the second argument) or parseInt() may wrongly guess the radix value.

Solution 3:

You have mistake at this line:

var result = (parseInt(a.number) > parseInt(b.number));

it should be:

var result = (parseInt(a.number) - parseInt(b.number));

sort accepts callback, which should return negative number, positive number or zero. In your code when result is true the function sortPlayers returns true.

Since if result is 0a.number and b.number will be equal your function could be transformed to:

functionsortPlayers(a, b) {
    var result = (parseInt(a.number) - parseInt(b.number));
    if (!result) {
      result = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
    }
    return result;
 }

Post a Comment for "Javascript Sort() Isn't Working For Arrays Of More Than 10 Objects In Chrome"