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:
- I’m fairly new to Javascript, so the better answer is one that explains more/I learn the most from.
- I haven’t played with jQuery yet, so a solution that avoids that is preferable. If there’s no way to do this without jQuery, guess I’ll have to learn it.
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.