Reputation: 39522
I have an array of Objects known as players, which is sorted often (so the index of a certain player will change every round). After two players finish a game, I want to update their objects with new scores. The only way I can think to do this (I'm new to Javascript) is the O(n) algorithm:
function updatePlayer(player){
for(var i=0;i<players.length;i++)
{
if(players[i].name === player.name)
players[i] = player;
}
}
I know arrays have O(1) access times, is there some function I can use to reduce the order of this (Perhaps even eliminate the need for this function altogether)?
Useful info:
Upvotes: 1
Views: 91
Reputation: 647
One way would be to extend the Player object yourself.
For example, if Player was defined as:
function Player(newName) {
this.name = newName;
}
You could extend it with the prototype property.
Player.prototype.index = 0;
At this point, every Player object would have a index property that would represent location in the array.
There are other ways I could think of doing something like this, but this was the top of my head thought.
Upvotes: 2
Reputation: 46647
Store your players as an object instead of an array. Then you can access players by name (or some other unique key):
var players = {
"Player1": {
"Score": 0,
"OtherStuff": "test"
},
"Player2": {
"Score": 100,
"OtherStuff": "test"
},
"Player3": {
"Score": 5,
"OtherStuff": "test"
}
};
for (player in players) {
alert('player ' + player + '\'s score is ' + players[player].Score);
}
Upvotes: 2
Reputation: 122356
Unless it's really a problem, I would leave it as it is. This sounds like premature optimization really.
How many players are there? And do you know this loop is slowing your application down? A for loop is quite common and this one certainly isn't computationally intensive.
You could indeed use a separate data structure for bookkeeping and fast access but you should only do that when it's really needed. The reason is that it takes effort to keep the data structures in sync, things may get buggy, et cetera.
Upvotes: 2
Reputation: 53607
If those are object, why not keep another array which the key is the name.
One array for sorting etc.
One array for fast access.
Upvotes: 2