Skip to content
Advertisement

.sort not working with Firefox

I wrote a Javascript app that I didn’t think any modern browser would have any issue with, but when I tested it, it worked fine with Chrome, Safari, Opera, even IE… but not Firefox.

This is the sort in question:

var sorted = Object.keys(teams).sort(function(a, b) {
    return -(teams[a][sortBy] < teams[b][sortBy])
});

Here’s a JSfiddle I made to demonstrate – http://jsfiddle.net/Aq6sc/1/

What that fiddle should do, is when you click on one of the categories, it should show you 3 “columns”. The team name, the category name, and the category value. They should print sorted by category value ascending. And it does in every browser except Firefox.

Advertisement

Answer

Your comparison function should return a negative number if the left operand comes before the right one in the sort order, a positive number if the right operand comes first, and 0 if they are equal. Your function only returns -1 or 0. Use this:

var sorted = Object.keys(teams).sort(function(a, b) {
    var l = teams[a][sortBy], r = teams[b][sortBy];
    return (l < r) ? -1 : ((l > r) ? 1 : 0);
});

http://jsfiddle.net/Aq6sc/4/

Here’s a version that behaves exactly the same but might be considered a little more readable:

var sorted = Object.keys(teams).sort(function(a, b) {
    var l = teams[a][sortBy], r = teams[b][sortBy];

    if (l < r) { return -1; }
    if (l > r) { return 1; }
    return 0;
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement