javascriptreactjsreducees6-map

React - Calculating the bigger value between elements only working partially


I am comparing two different Teams to define which is the stronger. The comparison is made by calculating the average of the two team score, the team with the greater value is the stronger.

I have reproduced my case here: DEMO

These are the functions used

const getAverage = (league, team) => {
  if (isNaN(league[0][team])) return null;

  return league.map(x => x[team]).reduce((a, c) => a + c) / league.length;
};

const maxAverage = (league, teams) => {
  return teams
    .map(team => {
      return {
        team: team,
        avg: getAverage(league, team)
      };
    })
    .reduce((a, b) => (a.avg > b.avg ? a : b)).team;
};


<p>Stronger Team:{maxAverage(this.state.selectedLeague, [this.state.selectedHomeTeam,this.state.selectedAwayTeam])}</p>

As you can see in the demo, it only works partially.

For example if i compare and select Atletico against Barcelona, it defines Barcelona stronger which is wrong ( -2 is not bigger than 0 ) but in the other way around selecting Barcelona against Atletico it defines Atletico stronger which is correct ( 0 is bigger than -2 ).

Where is my problem and how can i fix it?


Solution

  • On your maxAverage function, you should be referencing the exact league you would want to select on your scores object.

    Previously, you were trying to pass the entire scores object, which consists of both the Liga and Premier arrays. Which is why it will return null when you try to run that method.

    Instead, you should be passing the selected league to the getAverage method, which accepts league as an array (not an object of arrays).

    This should be the required changes to your maxAverage function.

    const maxAverage = (league, teams) => {
      return teams
        .map(team => {
          return {
            team: team,
            avg: getAverage(scores[league], team)
          };
        })
        .reduce((a, b) => (a.avg > b.avg ? a : b)).team;
    };
    

    I have created a demo over here.