Del boy Del boy - 1 month ago 6
Javascript Question

For Loop with return won't exit

I have two arrays:

Matches

var matches = [
{ playerId: 1, matchId: 1 },

{ playerId: 2, matchId: 1 },

{ playerId: 3, matchId: 2 }];


Players

var players= [
{ name: "Ronaldo", id: 1 },
{ name: "Messi", id: 2 },
{ name: "Zlatan" id: 3 }];


I want to list all players who played on match with
matchId 1
;

for (i = 0; i < matches.length; i++) {

if (matches[i].matchId == 1)
{
var p = matches[i].playerId;
//alert(p);
var currentName = getPlayersInfo(p);
alert(currentName);

}
}

function getPlayersInfo(id){
var curID = id;
var name;
for (i = 0; i < players.length; i++) {

if (players[i].id == curID) {
name = players[i].name;
}
}

return name;
}


If I have just
alert(p);
instead of that I call
getPlayersInfo(p)
than I am getting
alert
two times with id
1
and
2
and that works fine but with
getPlayersInfo(p)
first
alert
is
Ronaldo
and than I am getting
alert
Messi
multiply times.

What I am doing wrong in
getPlayersInfo()
?

Answer

You are overwriting the same i variable (which is global) because you aren't declaring it with var. In your for loops, use

for (var i = 0; ...

Another solution would be

for (var i = 0, l = matches.length; i < l; i++) {
    var match = matches[i];
    if (match.matchId === 1) {
        var name = players.find(function(player) {
            return player.id === match.playerId;
        });
        alert(name); // note, could be "undefined"
    }
}

If you have to look players up by their ID regularly, consider creating a map (ES2015 syntax for brevity)

let playersById = players.reduce((map, player) => {
    map[player.id] = player;
    return map;
}, Object.create(null));

then you can simply reference

playersById[match.playerId];
Comments