Attempting to find the index of the parent array containing the object with the greatest value

I am currently enrolled in a Udemy JavaScript Course where I am going through all the coding exercises again using ES6.

Within my array of teams, each team is represented as an object. My goal is to compare these teams and determine the winner, while also ensuring that this functionality can easily adapt to adding more teams in the future.

The code snippet below showcases my progress thus far. I am looking to make it capable of evaluating any number of arrays, however, at the moment it only assesses the first two arrays.

class Team {
    constructor(teamName, scores) {
    this.teamName = teamName,
    this.scores = scores;
    this.avgScore = Math.floor(this.scores.reduce((prev, cur) => (prev + cur) / this.scores.length));
    }
}
 
// Generating random scores
randomNumber = () => parseInt(Math.random() * 250);
randomScore = () => [randomNumber(), randomNumber(), randomNumber()];
 
// Creating the teams
let teams = [
    new Team('Team John', randomScore()),
    new Team('Team Mike', randomScore()),
    new Team('Team Mary', randomScore())
]

 
// for debugging purposes
for (el of teams) {
    console.log(`${el.teamName}: ${el.avgScore}`)
}

// attempting to make this scalable
let winner = 0;
calcWinner = () => teams.reduce((prev, cur, index) => cur.avgScore > prev.avgScore ? winner = index : winner = winner);
calcWinner();
 
// More debugging
console.log(winner);
 
// Logging result to the console
console.log(`The team with the highest average is ${teams[winner].teamName}, with a score of ${teams[winner].avgScore}`)

Answer №1

There are a few mistakes to address in your code:

  1. Incorrect average calculation method:
this.avgScore = Math.floor(this.scores.reduce((total, current) => (total + current)) / this.scores.length);
  1. Improper code for determining the team with the highest average score:
let winner = team[0];
teams.forEach(team => {
  if(team.avgScore > winner.avgScore ) {
    winner = team; 
  }
});

console.log(`Team name: ${winner.teamName} , Average Score: ${winner.avgScore}`)

Answer №2

You forgot to set and return the previous highest score in the reduce method. Start by initializing prev to zero within the reduce method. Then assign the highest score to prev if cur.avgScore is greater than prev. Remember, the syntax for array.reduce is: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

class Team {
  constructor(teamName, scores) {
    (this.teamName = teamName), (this.scores = scores);
    this.avgScore = Math.floor(
      this.scores.reduce((prev, cur) => prev + cur) / this.scores.length
    );
  }
}

// Generating random scores
randomNumber = () => parseInt(Math.random() * 250);
randomScore = () => [randomNumber(), randomNumber(), randomNumber()];

// Creating teams
let teams = [
  new Team("Team John", randomScore()),
  new Team("Team Mike", randomScore()),
  new Team("Team Mary", randomScore()),
];

// Debugging purposes
for (el of teams) {
  console.log(`${el.teamName}: ${el.avgScore}`);
}

// Making it scalable
let winner = 0;
calcWinner = () =>
  teams.reduce((prev, cur, index) => {
    if (cur.avgScore > prev) {
      winner = index;
      prev = cur.avgScore;
    }
    return prev;
  }, 0);
calcWinner();

// More debugging
console.log(winner);

// Logging result to the console
console.log(
  `The team with the highest average is ${teams[winner].teamName}, with a score of ${teams[winner].avgScore}`
);

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

Showing and hiding elements inside a loop with AngularJS using ng-if and ng

While presenting a separate div based on a condition inside ng-repeat, I encountered an error message that reads "Syntax Error: Token '<' not a primary expression at column 32 of the expression [widget.Type == 'Bar'>". How can thi ...

Retrieving the variable value instead of a reference using Ajax in ASP

After spending nearly two days trying to figure out this code and researching every possible solution, I still haven't been able to get it to work properly. It's likely that I'm implementing it incorrectly or missing something, so I've ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

Anomalous behavior of buttons in react-redux

Currently, I have a basic counter set up in react-redux as part of my learning process with these frameworks. My goal is to create a pair of number input fields that determine the payload for an increment/decrement action sequence. The intended outcome is ...

Why Next.js and MongoDB (minus Mongoose) is giving back an empty array

I am currently learning how to use API routes in Next.js with sample data retrieved from MongoDB. My challenge lies in attempting to retrieve data from a single object, which is proving more difficult than expected as I am new to working with MongoDB. Aft ...

What is the best way to transfer information from a child Angular app to a parent non-Angular app

If I have a plain JavaScript parent application with a child Angular application, how can I notify the parent application of any data changes in the child Angular application? The child application is loaded in a div, not in an iframe. ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

Accessing ExpressJS from AngularJS through local server

My latest project involves building a Web Application using AngularJS and ExpressJS. In this application, I have set up a GET "/" route in my app.js file to render the index.html page when accessed. One interesting feature is the GET "/test-data" route in ...

Change the numpy array to include nested arrays

I am working with a multidimensional numpy array of dtype object, containing arrays within it. To illustrate, consider the following code snippet showcasing this behavior: arr = np.empty((3,4,2,1), dtype=object) for i in range(arr.shape[0]): for j in r ...

I am looking to filter an array to only include products with IDs that match those in the first array

I'm attempting to filter an array to only include products with IDs found in another array. Here's what I've tried so far: let first = [1, 4] let second = [{id: 1}, {id: 2}, {id: 4}] second.filter((es, i) => es.id.includes(first)) https: ...

Data has been successfully acquired through the query, however, it cannot be accessed via the GraphQL API

After successfully building the API with Apollo Server and verifying its functionality in GraphiQL, I proceeded to make requests to the API from a front-end React app using Apollo Client. const [getUserPosts, { loading, error, data }] = useLazyQuery(GET_US ...

What is the best way to set a limit depending on whether a user is currently logged in or not?

I'm facing a challenge while using express and express-rate-limit to restrict download limits for anonymous users. The interesting part is that I want to deactivate the limit if the user object sent with the request is true. How can I achieve this? Be ...

The names() method of JSONObject is producing unreliable outputs

My goal is to retrieve the high level branches of JSONObject by using the names() method (which are dates in DD.MM.yyyy format in this example), then store this result as an ArrayList after running a standard for loop and sending it to a ViewPager adapter. ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Issue encountered! The command "npm run build" resulted in an exit status of 1 during the deployment of a website via the vercel command

I have been attempting to deploy a website on Vercel from my VSCode command line using the following command: vercel Upon executing this command, I receive the following output: https://i.sstatic.net/JK9CY.png When I run: vercel logs demo-minting-fronten ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

Which file from Next.js should I statically serve using Node?

Whenever I work with React, my standard process includes running npm build, moving the content to a directory named public in Node, and then including the following code snippets: node/app.js app.use(express.static(path.join(__dirname, 'public') ...

Modify the value of a variable inside another {{variable}} (not sure what it's called)

I am looking to update the variable "prefs" to reflect either "easy, medium, or hard" options based on user interaction. For instance: THIS {{choice.prefs.title}} NEEDS TO BE UPDATED TO {{choice.easy.price}} or {{choice.medium.price}} or {{choice.hard. ...

Dynamic search results with AngularJS, HTML, and Bootstrap components

I am in need of an interface element to display search results. My ideal scenario is for a textbox to be shown initially, and then as the user begins typing, the search results will appear in a list format. My first thought was to use a combo-box with a s ...

Encountering difficulty extracting information from an XML document within the Parse Cloud utilizing the XMLReader in an Express application

My goal is to extract elements from an XML file that I have already stored on the Parse Cloud for my Express app. I began coding after finding a helpful resource on using XMLReader with XPath on cloud code, as well as a guide on Parse httpRequest for retri ...