0

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() ?

2
  • What is players? Where is that defined? Commented Oct 19, 2016 at 22:02
  • @Phil I edited now Commented Oct 19, 2016 at 22:15

1 Answer 1

4

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];
Sign up to request clarification or add additional context in comments.

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.