Hi,
Can anyone explain how I can write a function to calculate total goals scored for the season by a given team from the following data i’m fetching from an api.
I’m trying to use map, filter and reduce but need to get the teams home and away goals.
My effort so far is:
function run (teamName){
function getSum (total, match) {
return total + match.score1;
}
fetch(url)
.then(response => response.json())
.then(data => console.log(data.rounds.map( matchday => matchday.matches.filter(match => match.team1.name === teamName).reduce(getSum))));
}
Sample of data returned (there are 10 matchdays):
{
"name": "English Premier League 2014/15",
"rounds": [
{
"name": "Matchday 1",
"matches": [
{
"date": "2014-08-16",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 1,
"score2": 2
},
{
"date": "2014-08-16",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"score1": 2,
"score2": 2
},
{
"date": "2014-08-16",
"team1": {
"key": "qpr",
"name": "Queens Park Rangers",
"code": "QPR"
},
"team2": {
"key": "hull",
"name": "Hull City",
"code": "HUL"
},
"score1": 0,
"score2": 1
},
{
"date": "2014-08-16",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2014-08-16",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 2,
"score2": 2
},
{
"date": "2014-08-16",
"team1": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 0,
"score2": 1
},
{
"date": "2014-08-16",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 2,
"score2": 1
},
{
"date": "2014-08-17",
"team1": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 1
},
{
"date": "2014-08-17",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 2
},
{
"date": "2014-08-18",
"team1": {
"key": "burnley",
"name": "Burnley",
"code": "BUR"
},
"team2": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"score1": 1,
"score2": 3
}
]
},