Reputation:
I have an array of objects that contains hockey matches and I need to get through them to create scoreboard in another array of objects.
I give you example.
I'd have array for example like this:
let array = [
{team1:"Toronto", team2:"Oilers", score1:5, skore:0},
{team1:"Toronto", team2:"Rangers", score1:3, skore:1},
{team1:"Toronto", team2:"Penguins", score1:0, skore:1},
{team1:"Oilers", team2:"Rangers", score1:2, skore:2},
{team1:"Oilers", team2:"Penguins", score1:2, skore:3},
{team1:"Rangers", team2:"Penguins", score1:0, skore:0}
]
And I'd need a function that would get me array like this:
let array2 = [
{Team:"Toronto", Wins:2, Draws:0, Losses:1, ShotGoals:8, RecievedGoals:2},
{Team:"Oilers", Wins:0, Draws:1, Losses:2, ShotGoals:4, RecievedGoals:10},
{Team:"Penguins", Wins:1, Draws:1, Losses:2, ShotGoals:2, RecievedGoals:4},
{Team:"Rangers", Wins:1, Draws:2, Losses:0, ShotGoals:3, RecievedGoals:2},
]
I tried to loop through the array with forEach and push new or change existing teams in the array2 but can't get it working as the array2, that I'm creating is changing, as the loop goes. It also needs to be dynamic so it still works if the first array is extended etc. and I'm just not able to make it work right now.
I'm assuming I will have to use some array methods but I can't seems to figure out which one and how as I am quite new to this.
Any help is highly appreciated. Thank you.
Upvotes: 0
Views: 49
Reputation: 735
let array = [
{team1:"Toronto", team2:"Oilers", score1:5, skore:0},
{team1:"Toronto", team2:"Rangers", score1:3, skore:1},
{team1:"Toronto", team2:"Penguins", score1:0, skore:1},
{team1:"Oilers", team2:"Rangers", score1:2, skore:2},
{team1:"Oilers", team2:"Penguins", score1:2, skore:3},
{team1:"Rangers", team2:"Penguins", score1:0, skore:0}
]
let result = {};
let addToTeam = (t,w,d,l)=>{
if(result[t] == null)
return result[t] = {team:t,wins:w,draws:d,losses:l}
result[t].wins+=w
result[t].draws+=d
result[t].losses+=l
}
array.forEach(m => {
if(m.score1>m.skore){
addToTeam(m.team1,1,0,0)
addToTeam(m.team2,0,0,1)
}else if(m.score1<m.skore){
addToTeam(m.team1,0,0,1)
addToTeam(m.team2,1,0,0)
}else{
addToTeam(m.team1,0,1,0)
addToTeam(m.team2,0,1,0)
}})
result = Object.values(result)
console.log(result);
results in
[{"team":"Toronto","wins":2,"draws":0,"losses":1},
{"team":"Oilers","wins":0,"draws":1,"losses":2},
{"team":"Rangers","wins":0,"draws":2,"losses":1},
{"team":"Penguins","wins":2,"draws":1,"losses":0}]
Upvotes: 1