Ludo
Ludo

Reputation: 5280

Best way to return the key of an array about the value of one of its containing objects

I would like to know what is the better way to exectute this common action:

var id = 1;
var Players = [{ id: 0, other: '...'}, { id: 1, other: '...' }]

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

I was thinking about Array.map but i don't know if we can access the key:

Players.map(function(Player) { if (Player.id == id) { return ?? } });

Upvotes: 0

Views: 63

Answers (3)

kalley
kalley

Reputation: 18462

You could also try reduce:

// The second argument is set to null so that reduce doesn't just
// start with the first object in the array
Players.reduce(function(memo, Player, key) {
    return Player.id === id ? key : memo;
}, null);

Upvotes: 1

Depending on your structure (and keeping performance in mind); making it an associative object/array could work out.

var object = { id: 1, other: '...' };

var Players = [];
Players[object.id] = object;

You can then reference the required Player by ID by doing:

var id = 1;
var playerObject = Players[id];

Please note that you cannot use negative or zero values for the ID in this case.

Upvotes: 1

SLaks
SLaks

Reputation: 887315

Array.map() passes the index as the second parameter to the callback.
However, it won't help you find a single item.

Javascript arrays do not have a function that does this.

Using LoDash, you can do this very easily:

_.findIndex(Players, { id: 4 })

Upvotes: 0

Related Questions