Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format:

results:[
{
Group:"A"
Home: "Fc Barcelona",
Away: "Fc Porto"
Score: {
Home: 0,
Away: 0
},
{
Group:"A"
Home: "AC Milan",
Away: "Fc Barcelona"
Score: {
Home: 0,
Away: 1
},

{
Group:"A"
Home: "FC Barcelona",
Away: "AC Milan"
Score: {
Home: 2,
Away: 0
}
{
Group:"B"
Home: "Juventus",
Away: "Real Madrid"
Score: {
Home: 0,
Away: 1
}
]

However, I am facing issues with team duplicates and calculating points. I want to generate standings tables based on groups but can't sum up points of a team from multiple games using scores.

I have tried using if statements as shown in the code snippet provided, but it's not giving me the desired output. If you have a better solution, please share!

<tbody v-for="result in results" :key="result.index">
    <div v-if="result.Group=='A'>
       <tr>
         <td>{{result.Home}}</td> <br> <-- need each team to be printed only once

        <td>{{result.Score.Home}}</td> <-- logic needed to calculate and display points here based on score

                        </tr>
                    </div>
                </tbody>

data () {
    return {
        results:[]
    }

mounted () {
    axios
      .get('http://localhost/soccer/results',)
      .then(response => (this.results = response.data))
}

The current output shows duplicated teams with their respective scores:

Team         Score      PTS
Fc Barcelona 0
Ac Milan 0 
Fc Barcelona 2

However, my goal is to display teams along with their total points like this:

Team         Score      PTS
Fc Barcelona  N/A       3
Ac Milan      N/A       0

Answer №1

For resolving your issue, here is an illustration utilizing console.log. Your dataset comprises varying names for the same club (Fc Barcelona, FC Barcelona). Utilize functions like toLowerCase or toUpperCase for standardizing your data.

const groupBy = function(items, keyField) {
  return items.reduce(function(result, item) {
    (result[item[keyField]] = result[item[keyField]] || []).push(item);
    return result;
  }, {});
};

const gamesData = [
{
Group:"A",
Home: "FC Barcelona",
Away: "FC Porto",
Score: {
Home: 0,
Away: 0
},
},
{
Group:"A",
Home: "AC Milan",
Away: "FC Barcelona",
Score: {
Home: 0,
Away: 1
},
},
{
Group:"A",
Home: "FC Barcelona",
Away: "AC Milan",
Score: {
Home: 2,
Away: 0
},
},
{
Group:"B",
Home: "Juventus",
Away: "Real Madrid",
Score: {
Home: 0,
Away: 1
}
}
]

const groupedGames = groupBy(gamesData, 'Group')


const mapResults = new Map()

for(let gKey in groupedGames) {
  const groupValue = groupedGames[gKey]
 const resultsMap = new Map()
  
  groupValue.forEach(game => {
  if (!resultsMap.has(game.Home)) {
    resultsMap.set(game.Home, { pts: 0 })
    } 
    let homeTeam = resultsMap.get(game.Home)
    
    if (!resultsMap.has(game.Away)) {
    resultsMap.set(game.Away, { pts: 0 })
    } 
    let awayTeam = resultsMap.get(game.Away)
    
    if (game.Score.Home === game.Score.Away) {
    homeTeam.pts += 1
      awayTeam.pts += 1
    }
    
    if (game.Score.Home > game.Score.Away) {
    homeTeam.pts += 3
    }
    
    if (game.Score.Home < game.Score.Away) {
    awayTeam.pts += 3
    }
  })
  
  mapResults.set(gKey, resultsMap)
}

mapResults.forEach((val, k) => {
console.log('Group:', k)
  
  val.forEach((v, key) => {
  console.log('Club:', key, 'Points:', v.pts)
  })
})

Lastly, the output would be:

Group: A
Club: FC Barcelona Points: 7
Club: FC Porto Points: 1
Club: AC Milan Points: 0
Group: B
Club: Juventus Points: 0
Club: Real Madrid Points: 3

Answer №2

Instead of processing the data in real-time, create a template based on the expected format and then develop a function to convert the incoming data into that structure.

In my scenario, I aimed to group the data by teams within their respective groups, resulting in nested objects.

const axiosPromise = Promise.resolve([{
    Group: "A",
    Home: "Fc Barcelona",
    Away: "Fc Porto",
    Score: {
      Home: 0,
      Away: 0
    }
  },
  {
    Group: "A",
    Home: "AC Milan",
    Away: "Fc Barcelona",
    Score: {
      Home: 0,
      Away: 1
    }
  },
  {
    Group: "A",
    Home: "FC Barcelona",
    Away: "AC Milan",
    Score: {
      Home: 2,
      Away: 0
    }
  },
  {
    Group: "B",
    Home: "Juventus",
    Away: "Real Madrid",
    Score: {
      Home: 0,
      Away: 1
    }
}
]);

new Vue({
  el: '#app',
  data: {
    groups: {}
  },
  mounted() {
    axiosPromise.then((results) => this.transformResults(results));
  },
  methods: {
    transformResults(axiosResults) {
      const result = {};
      axiosResults.forEach((obj) => {
        if (!(obj.Group in result)) {
          result[obj.Group] = {};
        }
        const g = result[obj.Group];
        if (!(obj.Home in g)) {
          g[obj.Home] = 0;
        }
        if (!(obj.Away in g)) {
          g[obj.Away] = 0;
        }
        g[obj.Home] += obj.Score.Home;
        g[obj.Away] += obj.Score.Away;
      });
      this.groups = result;
    }
  }
});
table {
  border-collapse: collapse;
  margin: 1rem 0;
  outline: thin solid black;
}

th,
td {
  border: thin solid gray;
  padding: 0 0.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(g, name) in groups">
    Group: {{name}}
    <table>
      <tr>
        <th>Team</th>
        <th>Points</th>
      </tr>
      <tr v-for="(points, name) in g">
        <template v-if="points > 0">
          <td>{{name}}</td>
          <td>{{points}}</td>
        </template>
      </tr>
    </table>
  </div>
</div>

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

Trying to incorporate a PHP echo statement into the innerHTML of a button is ineffective

I have a piece of jQuery code that is not functioning as expected: $("#erase").click(function(){ $("#erase").attr("disabled", "disabled"); // Prevent double-clicking $(this).html("Erasing..."); $.post("erase.php", {target: $("#targ ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

Achieving stylish CSS effects on dynamically loaded content post AJAX request

I am currently developing an application that utilizes AJAX to fetch JSON data and then uses an ES6 template literal to construct the view. It's a simple demonstration: let mountPoint = document.getElementById("mountPoint"); let view = document.cre ...

Sending an array of dictionary objects to a JavaScript function

I have a situation where I need to pass a large amount of data stored in an NSArray containing NSDictionary objects to a JavaScript function using a webview and the method: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script My inquir ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

What is the reason for the failure of this react ternary return statement?

My slideboard is set up to show a warning component (currently just a "test" div) when the prop "columnsItem" exceeds 50. Everything works fine, but when I switch back to a slideboard with fewer columns, all I see is a blank white screen. Can you help me ...

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

Are there any testing frameworks available for JavaScript that are similar to Junit and specifically designed for testing object-oriented JavaScript within Node

What are some recommended methods for testing object-oriented JavaScript in Node.js? For instance, let's consider the following Cat.js class: function Cat(age, name) { this.name = name || null; this.age = age || null; } Cat.prototype.getAge ...

Guide to designing a bar graph using HTML5 for a web app optimized for iPad

I am in the process of converting my iOS native app for iPad to a web app using HTML5. However, I am encountering an issue with creating a bar graph for the HTML5 app. Is there any documentation or built-in API available for this specific task? On iOS, we ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Tips for preventing HTML ID clashes while integrating with the Document Object Model of external websites

When incorporating additional HTML elements into a webpage using Javascript or jQuery, along with external CSS declarations, it is important to avoid conflicts with existing IDs and class names already present on the page. This could lead to issues if ther ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...

Attempting to start and restart an asynchronous function using setIntervalAsync results in a TypeError because undefined or null cannot be converted to an

Recently, I've been working on creating a web scraper that utilizes data extracted from MongoDB to generate an array of URLs for periodic scraping using puppeteer. My goal is to make the scraper function run periodically with the help of setIntervalAs ...

Utilize JavaScript to append elements to an array in each loop iteration, gradually building a single, unified

I find myself in a situation where an async request is sending data to a child react component. Upon logging the "data" in the component, I receive multiple arrays sequentially. Ideally, I would prefer not to rewrite the request in the parent component and ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Creating a square shape in Twitter Bootstrap to frame an item on a webpage

I've been working on creating a webpage that looks similar to the image provided. I've managed to get about 90% of it done, but there are a couple of issues I'm facing: How can I create a square with a triangle at the bottom as shown in th ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

JS problem with using for and foreach loops in Node.js

I've been really stumped by this situation. Everything was running smoothly until 4 days ago when two of my cron daemon jobs suddenly stopped working. Instead of ignoring the issue, I decided to take the opportunity to rebuild and enhance the code. I ...