Reputation: 828
I have an object called "Player" with properties such as "score", "turns", "name", etc. Based on how many players the user chooses to have, I create an array of players.
As the game is played, I update each player's score. What I need to do is compare the "score" from the current player against all the other players. If it is higher, said player wins. Currently the only way I've been able to do this is to create a temporary array with the score values of all players and reorder the array from highest to lowest. I am then checking to see if the current player's score is the same as the score in the 0 index of my temp array. This can cause potential problems though, as two players COULD have the same score, at which point I have no way of correlating the score in the temp array with the player to whom it belongs to.
Is what I'm currently doing the best possible choice? There has to be a way to optimize this. Thanks for any help!
Upvotes: 0
Views: 1608
Reputation: 1533
Why can't you iterate over the array of players and simply check the score of each versus the current player?
Instead of keeping an Array of scores could you keep an array of players sorted by their score?
Does this help?
http://www.javascriptkit.com/javatutors/arraysort2.shtml
Upvotes: 0
Reputation: 707218
You could just look through the array for the highest score and then see if that's your player or not.
var playerInfo = [
{name: "Bob", score: 70},
{name: "Jill", score: 98},
{name: "Ted", score: 96}
];
function findHighestScore() {
// assumes there is always at least one entry in the playerInfo array
var highestIndex = 0;
var highestScore = playerInfo[0].score;
for (var i = 1; i < playerInfo.length; i++) {
if (playerInfo[i].score > highestScore) {
highestIndex = i;
highestScore = playerInfo[i].score;
}
}
return(highestIndex);
}
Upvotes: 1