Josh
Josh

Reputation: 380

For loop using two variables?

I am working on some code where I have two variables with several different teams in them. I am new to JS and can't seem to understand how to print the value of both variables in the same for loop.

let jsonData = pm.response.json();
let home_team = []
let away_team = []
let home_team_id = []
let away_team_id = []
//console.log(jsonData)
jsonData.games.forEach((b)=>{
    home_team.push(b.home.name)
    away_team.push(b.away.name)

})

pm.environment.set("Home_Team",home_team)
pm.environment.set("Away_Team",away_team)
//console.log(pm.environment.get("Home Team"))
//console.log(pm.environment.get("Away Team"))

for (const element of home_team) {
  console.log(element + "VS" + away_team);
}

Now I know the code above will not run, I am just showing what I would like printed to console, I can't figure out how to add a second element that references away_team in the same looop. With that said when I set my for loop to

for (const element of home_team) {
  console.log(element);
}

It prints my list of home teams with no issues but I really am looking for a loop that prints both my home and away team, the list sizes are the same and always will be.

Thanks in advance.

Upvotes: 0

Views: 79

Answers (2)

Praneet Dixit
Praneet Dixit

Reputation: 1425

If both of your arrays contain same number of items, then you can use an ordinary for loop with accessing each item with the same index as below -

let home_team = ["A", "B", "C"];
let away_team = ["D", "E", "F"];

for(let i=0; i<home_team.length; i++){
  console.log(`${home_team[i]} VS ${away_team[i]}`);
}

Alternatively, you can also use multiple counters in a for loop as below (though you won't need this now -

let home_team = ["A", "B", "C"];
let away_team = ["D", "E", "F"];

for(let i=0,j=2; i<home_team.length; i++, j--){
  console.log(`${home_team[i]} VS ${away_team[j]}`);
}

Upvotes: 1

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

Just use an indexed for loop

for(let i = 0;i < home_team.length; i++) {
  console.log(home_team[i] + "VS" + away_team[i]);
}

You can also use forEach

home_team.forEach((item, index) => console.log(item + "VS" + away_team[index]));

Upvotes: 2

Related Questions