What is causing this code to not produce the expected result of 8.675?

Recently, I encountered a challenge on freecodecamp

I managed to write the code successfully, but unfortunately, my browser crashed and I lost all the progress. When I attempted to rewrite the code, it was returning an incorrect answer (a value of 2).

I'm seeking assistance to understand why this is happening without directly giving me the solution. Can you provide insight into what might be causing this issue and how it can be fixed? That's all I require.

Below is the code snippet in question:

// the global variable
var watchList = [{
    "Title": "Inception",
    "Year": "2010",
    ...
    
// Add your code below this line
var arr = [];
watchList.map(item => {
  if (item.Director === "Christopher Nolan") {
    arr.push(Number(item.imdbRating));
  }
});
var averageRating = arr.reduce((before, after) => {
  return (before + after) / arr.length;
});

// Add your code above this line

console.log(averageRating);

If this question doesn't belong here or if there are any errors in my approach, please let me know so I can correct them accordingly.

Answer №1

Your code contains a logical error causing it to return incorrect values. The issue lies in dividing the average rating by the array length each time you iterate over the array using reduce.

return (before + after) / arr.length;

The corrected approach is:

return (before + after);

Then, divide by the array length at the end like so:

averageRating = averageRating/arr.length;

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

The toggle button for columns is not triggering the callback action

When working with the following JSFiddle, I noticed that the action function does not seem to fire whenever a button to select a column in the column visibility tool is selected. Check out the code snippet below for reference: $(document).ready(function( ...

Express JS with multer is unable to process multiple file uploads, resulting in an empty array being

As I develop an app on Glitch with express js, the functionality requires users to upload multiple files. Here is the code snippet that I am using: var express = require('express'); var cors= require('cors'); var bodyParser= requir ...

Steps to stop POST requests sent via AJAX (acquired through Firebug)

Is there any way to protect against users spamming a post request? Consider a scenario where a form is submitted through an Ajax post. I've observed that the post request can be duplicated by simply right clicking on it and choosing "open in a new tab ...

updating a div with URL redirection instead of global redirect

I am facing an issue with redirecting my website flow to the login page when a user clicks any link on the page after the session has expired (either due to timeout or manual logout from another window). In an attempt to solve this, I inserted the followi ...

Utilizing JavaScript within the Spring MVC form tag

Can you please assist me with the following question? I am currently working on a project using JSP, where we are utilizing Spring form tags. My issue involves creating two radio buttons that, when clicked, will display different options and pass the sele ...

Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out ...

Discover the method for measuring the size of a dynamically generated list

I'm currently working on a chat box that displays messages as a list. One issue I'm facing is that when I click on the start chat button, the chat box opens but the length of the list always remains zero. How can I resolve this problem? $(docu ...

Issue encountered while attempting to assign multidimensional arrays in a loop: the expression must be a modifiable lvalue

Within a class, there exists an array structured as follows: public: int playGrid[10][10];//grid size of 10x10 or 100 squares When executing the following code snippet: for (int i = iX1; i < iX2; i++) { if (i == iX1) ...

Executing JQuery and Ajax calls within a loop

Can I dynamically change the variable in ("xxxxx").html(data) inside a for loop? I've been struggling to figure this out. My goal is to populate an HTML table with JSONP data from multiple ajax calls within a loop, where the URL changes each time. Wh ...

Even after refreshing the page, Chrome stubbornly insists on showing the old data

I've been working on a single-page application where one page triggers server requests every time it loads. After making changes and deploying them, I noticed that the live version of the application was not reflecting the updates. Even though the cha ...

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...

Determine whether the text entered is present in the dropdown list

I am currently working with Prestashop 1.7 and have encountered an issue with the Search by Brand functionality in the ps_facetedSearch module. While it works perfectly under the dropdown list form, I need to override this search and use an input field ins ...

Exploring the power of Firebase with Vue Js lifecycle methods

I am attempting to retrieve data from a specific user in Firebase and push that data into designated input fields. The path in Firebase is located here: var query = db.ref('Clients/'+ clientName +'/form/'); I retrieve the data in the ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

Personalized scrollbar extends beyond the screen

I have been working on creating my own scroll bar, and for the most part, it's functioning well. However, there is one small issue that I'm facing. Whenever I reach the bottom of the page, the handle of the scroll bar disappears underneath the v ...

Encountering a problem with NodeJS and ExpressJS Router.use()

Encountering an Error: // Necessary module imports // Setting up view engine app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.ur ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

When I click the back button on my mouse in React, it returns JSON data instead of HTML and CSS

I am working on a web application with two pages: a menu and orders. When I navigate from the orders page to the menu page and click the back button, I receive JSON data instead of the HTML page. The data loads correctly, but the page does not display the ...