1

I am currently doing a golf scorecard application and I'm looking to sort each players results array by their overall score.

e.g, if I have the following arrays:

array1 = {
    name: "player1",
    overall: -3
}

array2 = {
    name: "player2",
    overall: -1
}

How can I sort them so that I can output the rank of each player depending on who got the best score while also keeping the name value?

Any help would be greatly appreciated.

1
  • 2
    Those are objects, not arrays. Make an actual array of such objects and sort the array using its .sort method (var players = [{name: ...}, {name: ...}];). Commented Apr 15, 2016 at 13:03

1 Answer 1

2

With a proper data structure for Arrays, you can sort them with Array#sort.

var object1 = { name: "player1", overall: -3 },
    object2 = { name: "player2", overall: -1 },
    array = [object1, object2];

array.sort(function (a, b) { return a.overall - b.overall; });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

3 Comments

OP probably wants them sorted in opposite order, I'm guessing.
@MarkReed, "*output the rank of each player depending on who got the best score *", more negative value is good ...?
Yup. It's golf. The lower the score, the better.

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.