jenswirf
jenswirf

Reputation: 7317

Why is the sorting of this object array failing?

I'm trying to sort this object by the score value so I can populate a highscores table. Found this method of sorting which works lovely for sorting smallest to highest with a - in the formula, but when I try and reverse it with a + it doesn't work. I'm confused..

JS:

scores = [
        {"n":"Arne", "score":700},
        {"n":"Bertil", "score":430},
        {"n":"Carl", "score":901},
        {"n":"David", "score":30},
        {"n":"Eric", "score":23},
        {"n":"Frida", "score":118},
        {"n":"Greg", "score":221},
        {"n":"Hulk", "score":543}
        ];

scores.sort(function(a, b) {
return a.score + b.score;
});

//add rows to table from scores object
var t = document.getElementById('table');
for (var j in scores) {

        var r = document.createElement('tr')
        r.innerHTML = '<td><span></span></td><td>'+scores[j].n+'</td><td>'+scores[j].s+'</td>'
        t.appendChild(r);
}

Upvotes: 0

Views: 75

Answers (3)

daniel_aren
daniel_aren

Reputation: 1924

According to http://www.w3schools.com/jsref/jsref_sort.asp you can see that you just reverse the input parameters like this: return a.score - b.score;

Upvotes: -1

Platinum Azure
Platinum Azure

Reputation: 46193

You mention that you're trying to reverse the sort, which originally involved subtraction.

Thus I think it's fair to assume that your original sort was like this...

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

If you want to sort in the opposite direction, simply reverse the order of the subtraction:

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

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148524

your sort function should return positive , 0 , or negative values

you probably trying to add some numbers there which is a mistake.

try here :

http://jsbin.com/icojaz/edit#javascript,html

it sorts by score.

Upvotes: 0

Related Questions