Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  42] [ 7]  / answers: 1 / hits: 5442  / 11 Years ago, sat, january 11, 2014, 12:00:00

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.


More From » javascript

 Answers
32

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

[#48793] Friday, January 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailey

Total Points: 355
Total Questions: 91
Total Answers: 91

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;