0

I'm making an online game where users have different ID's.

Here's the client code for creating a new player:

var newPlayer = function(id){
   return player[player.length]={
      x:0,
      y:0,
      id:id
   }
}

newPlayer(50) would create a player with the ID 50.

How do I select that player based on its id variable?

Thanks

3 Answers 3

2

The storage of a JavaScript array can be sparse so you can just do the following:

function newPlayer(id) {
  return player[id] = { x:0, y: 0, id: id };
}

function findPlayer(id) {
  return player[id];
}

This results in a at worst, O(log N), but probably close to O(1), lookup at the cost of potentially more storage.

Chuck.

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

Comments

0

Create a function, iterate the array, return once found

function findPlayer(id) {
    for (var i = 0; i < player.length; i++) {
        if (player[i].id == id) return player[i];
    }
}

Comments

0
var player = [];
newPlayer(123);
newPlayer(234);

Using Underscore or Lodash (or vanilla JS, if you prefer):

var player123 = _.findWhere(players, { id: 123 });

Etc.

If you will only ever search by id, and id is unique among all players, you could store the players in a key-value object instead of an array:

function newPlayer(id) {
    player[id] = { x: 0, id: id }
}

Lookup via:

var player123 = player[123];

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.