Total number of goals scored by a single team (extracted from JSON data)

My data consists of football games in a JSON file

[
   {
      "game_id":"258716",
      "game_date_start":"2016-08-15",
      "season": "2016",
      "team_1_id":"119",
      "team_2_id":"120",      
      "team_1_goals_quantity":"2",
      "team_2_goals_quantity":"1",         
   },
   {
      "game_id":"258717",
      "game_date_start":"2016-09-15",
      "season": "2016",
      "team_1_id":"119",
      "team_2_id":"122",      
      "team_1_goals_quantity":"1",
      "team_2_goals_quantity":"1"     
   },
   {
      "game_id":"258718",
      "game_date_start":"2016-07-15",
      "season": "2016",
      "team_1_id":"121",
      "team_2_id":"119",     
      "team_1_goals_quantity":"1",
      "team_2_goals_quantity":"1"      
   }
]

I have completed Task #1 which counts the total number of games for each team

For Task #2, I am using Vue.js but unsure how to count the total number of goals for each team across all games. The challenge lies in the fact that the team's unique ID can be found in either team_1_id or team_2_id.

If you have any suggestions or solutions for Task #2, please share them with me.

Answer №1

If you prefer to maintain the code as is, consider incorporating an additional object for tracking goals in the following manner:

 function countGames() {
      var data = this.$store.getters.games;      
      var arr1 = []; 
      var goalsPerTeam = []; // keeping track of goals here
      var obj1 = {}; 

      //Fetching all unique Team IDs
      function getMatches() { 
              for (var i in data) {        
                    obj1[data[i].team_1_id] = (obj1[data[i].team_1_id] || 0) + 1;
                    obj1[data[i].team_2_id] = (obj1[data[i].team_2_id] || 0) + 1;
                    // adding goals count
                    if (goalsPerTeam[data[i].team_1_id] === undefined) {
                      goalsPerTeam[data[i].team_1_id] = parseInt(data[i].team_1_goals_quantity);
                    } else {
                      goalsPerTeam[data[i].team_1_id] += parseInt(data[i].team_1_goals_quantity);
                    }

                    if (goalsPerTeam[data[i].team_2_id] === undefined) {
                      goalsPerTeam[data[i].team_2_id] = parseInt(data[i].team_2_goals_quantity);
                    } else {
                      goalsPerTeam[data[i].team_2_id] += parseInt(data[i].team_2_goals_quantity);
                    }
              };      
              Object.keys(obj1).forEach(function(el, data) {
                  arr1.push( [ el, obj1[el], goalsPerTeam[el]] );  // updating this                   
              });                          
           }; 
        getMatches();          
        var result = arr1.map(
              // finally adding here
              ([team_id, matches, goals]) => ({team_id, matches, goals}) //resulting in { {team_id: "119", matches: 3}, {team_id: "120", matches: 1} ... }
        );
        return result;                 
      }  

Answer №2

To extract the necessary data, you can iterate through each object in the array and update the corresponding counters in this manner:

    let totalGames = {},
        totalGoals = {};

    data.map( game => {

        //count games for team 1
        if (!totalGames.hasOwnProperty(game.team_1_id)) {
            totalGames[game.team_1_id] = 1;
        } else {
            totalGames[game.team_1_id] += 1;
        }
        
        //count games for team 2
        if (!totalGames.hasOwnProperty(game.team_2_id)) {
            totalGames[game.team_2_id] = 1;
        } else {
            totalGames[game.team_2_id] += 1;
        }

        //calculate goals for team 1
        if (!totalGoals.hasOwnProperty(game.team_1_id)) {
            totalGoals[game.team_1_id] = parseInt(game.team_1_goals_quantity);
        } else {
            totalGoals[game.team_1_id] += parseInt(game.team_1_goals_quantity);
        }

        //calculate goals for team 2
        if (!totalGoals.hasOwnProperty(game.team_2_id)) {
            totalGoals[game.team_2_id] = parseInt(game.team_2_goals_quantity);
        } else {
            totalGoals[game.team_2_id] += parseInt(game.team_2_goals_quantity);
        }
    });

Answer №3

When it comes to tracking goals scored, my approach involves constructing a dictionary containing pairs of teams and their respective goal counts. This information is then transformed into an array featuring team-goal number combinations:

function trackTeamGoals(jsonObject){

   // generate a summarized JSON
   let summary = []
   for(let index in jsonObject){
      let team1 = {'team': jsonObject[index]['team_1_id'], 'goals': jsonObject[index]['team_1_goals_quantity']};
      let team2 = {'team': jsonObject[index]['team_2_id'], 'goals': jsonObject[index]['team_2_goals_quantity']};
      summary.push(team1)
      summary.push(team2);
   }

   // calculate the total goals per team using reduce and return
   let sumData = summary.reduce(function(accumulator, currentValue) {
      accumulator[currentValue.team] = accumulator[currentValue.team] || {'team_id': currentValue.team, 'goals': 0};
      accumulator[currentValue.team]['goals'] = accumulator[currentValue.team]['goals'] + parseInt(currentValue.goals);
      return accumulator;
   }, {})

   // return as an array
   return Object.keys(sumData).map(key => sumData[key])
}

Answer №4

Here's a simple way to achieve the desired outcome:

const fetchStatsByTeamId = (id) => {
  const games = list
    .filter((game) => game.team_1_id === id || game.team_2_id === id)

  const goalsScored = games
    .map((game) => game.team_1_id === id
      ? game.team_1_goals_quantity
      : game.team_2_goals_quantity)
    .reduce((total, goals) => total + parseInt(goals), 0)

  return {
    games: games.length,
    goals: goalsScored
  }
}

Then use it like so:

// Use string argument for team ID.
fetchStatsByTeamId('119') #returns { games: 3, goals: 4 }
fetchStatsByTeamId('120') #returns { games: 1, goals: 1 }
fetchStatsByTeamId('121') #returns { games: 1, goals: 1 }
fetchStatsByTeamId('122') #returns { games: 1, goals: 1 }

To summarize: Filter matches involving the specified team, calculate their goals, and provide the total stats.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Assign external data to component prior to rendering

When using Vue Router with file based components, I encountered an issue with rendering data from an API in a component called CaseDetail.vue. This component receives a parameter (slug) which is used to fetch a JSON from the API using axios. To handle thi ...

How to extract data from a JSON file in Java without relying on org.json library

I need help extracting the first element in the "key" array and its corresponding value from the given JSON data. I have come across examples using org.json, but it seems outdated. Can anyone suggest the best way to achieve this with the provided JSON file ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Python script to retrieve matching values on the same level of a JSON structure

I am facing a dilemma with my Python code that involves making an API call and receiving JSON data. My goal is to create a list in Python containing item IDs along with their matching descriptions. Below is a simplified version of the issue I am currently ...

Having trouble with submitting data in an ExpressJS POST request while using mongoose?

As I embark on building my first express.js application, I encounter my initial obstacle. The setup is rather simple. Routes in app.js: app.get('/', routes.index); app.get('/users', user.list); app.get('/products', product. ...

Implementing this type of route in Vue Router - What are the steps I should take?

I am currently delving into Vue and working on a project that involves creating a Vue application with a side menu for user navigation throughout the website. Utilizing Vue Router, my code structure looks like this: <template> <div id="app ...

Convert XML to JSON with Azure

Seeking assistance with transforming XML to JSON using Azure liquid mapping in order to extract the session ID. <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3. ...

Unable to trigger Vuejs click event when using v-if condition

I've encountered a strange issue. I'm attempting to trigger a method when an element is clicked in a v-for loop, but it doesn't seem to work when using v-if or v-show. Here's a sample of my HTML code: <div class="chosen-drop custom ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

What is the method for defining the current date variable within a .json object?

When using a post .json method to send an object, I encounter the following situation: { "targetSigningDate": "2021-09-22T21:00:00.000Z" } The "targetSigningDate" always needs to be 'sysdate'. Rather than manually c ...

Partially accessible Angular service within a callback function

I'm currently facing an issue in my Angular simple app related to a factory that is not fully available within a callback function. You can check out a simplified version of the application on this Plunkr link. Here's a snippet of the code: Th ...

Is there a way to configure my dropdown menu so that only one dropdown can be open at a time and it remains open when clicking on a <li> item?

I've been working on developing a dropdown menu that appears when clicked, rather than hovered over. I've managed to implement this functionality using JavaScript, and overall, it's working quite well. Currently, the menu shows or hides whe ...

What is the best way to trigger a JavaScript onclick event for a button that is located within a dropdown menu on an HTML page

I've implemented a feature that resizes the font size within a text area based on the selected font size. It was functioning flawlessly... until I decided to place the font size selection in a drop-down menu, which caused the feature to stop working. ...

What is causing the issue preventing me from running npm run dev on CentOS 7?

Currently facing an issue while trying to install my application on a new server after migrating from centos6 to centos7. When attempting to install a Laravel app, everything goes smoothly as it did on centos6, except for when I run npm run dev [root@v6-a ...

Sending data from a parent component to a child component through a function

In the process of developing an app, I have implemented a feature where users must select options from four dropdown menus. Upon clicking the "OK" button, I aim to send all the selections to a child component for chart creation. Initially, I passed the sel ...

Understand the nature of the reply

Can someone tell me the type of response an action controller will give before the instructions? respond_to do |format| format.html{ ... end Is it possible to determine this beforehand? Many thanks! ...