0

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

3 Answers 3

3

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;
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Technically your comparator results in undefined sort order, see the spec at 15.4.4.11, your function breaks half of those consistency requirements.
-1

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;

Comments

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.