What is the best method for summing the numerical values of a JSON array?

I have a task to calculate the sum and average of integer values from an Array object. Here is the input array:

Input: [
        {"string": "John", "integer": 7},
        {"string": "Margot", "integer": 8},
        {"string": "Jules", "integer": 4},
        {"string": "Marco", "integer": 19}
       ]

Output: 9.5

The issue I am facing is that even though I have created a function to calculate the average, it does not seem to be working correctly. Can someone help me debug this? The code snippet is provided below:

function calculateAverage(student_grades) {
    sum = 0;
    for(i = 0; i < student_grades.length; i++){
        sum += student_grades[i].integer;
    }
    return sum / student_grades.length;
};

var all_grades = [
        {"string": "John", "integer": 7},
        {"string": "Margot", "integer": 8},
        {"string": "Jules", "integer": 4},
        {"string": "Marco", "integer": 19}
       ]
console.log(calculateAverage(all_grades));

Answer №1

function calculate_student_average(grades) {
    total = 0;
    for( index = 0; index < grades.length; index++){
        total += grades[index].value;        
    }
    return total / grades.length;
};

Try incorporating array methods like map and reduce for a more concise solution

function calculate_student_average(grades) {
    total = grades.map(item => item.value).reduce((a,b) => a + b, 0)
    return total / grades.length;
};

Answer №2

Your solution is close, just remember to divide the sum by the length before returning it:

function calculateAverage(grades) {
  let sum = 0;
  let len = grades.length;
  for (let i = 0; i < len; i++) {
    sum += grades[i].value;
  }
  return Math.round(sum * 10 / len) / 10;
};


all_grades = [
        {"name": "Alice", "value": 8},
        {"name": "Bob", "value": 7},
        {"name": "Charlie", "value": 6},
        {"name": "David", "value": 5}
       ]
console.log(calculateAverage(all_grades));

Remember to always use var, let, or const to declare your variables.

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

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

Deleting an element in a multidimensional array based on a specific condition in PHP

A complex array structure is at hand: [0] => Array ( [id] => 55829 [date] => 2014-09-05 07:00:56 [customer] => Engineering [server] => example [status] => Successful [version] => 1 ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

Using jquery to loop through JSON objects based on their values

Looking to display the NBA Western Conference leaders by seed, I have utilized the JSON file available at: http://data.nba.com/data/v2014/json/mobile_teams/nba/2014/00_standings.json Here is the current setup: $(document).ready(function() { $.getJSON( ...

Modify the position of the CSS background for the Y-axis using jQuery

Let's consider a scenario with the following table: <table> <tr> <td class="t"></td> <td class="e"></td> <td class="s"></td> <td class="t"></td> </ ...

What are some strategies for preventing a child component from triggering a re-render of its parent component in React Native?

My child component is causing the parent component to re-render when it's clicked, which is not the desired behavior. I initially thought that removing all the setState() functions in the child component would prevent this, but then I realized that As ...

InfoWindow from JSON data not displaying in Google Maps V3

My current project involves using PHP to generate a JSON file from data stored in MySQL. One of the goals I have is to display certain pieces of this data in an information window on Google Maps whenever I click on a marker. Although I've managed to ...

ERROR: An issue occurred while attempting to resolve key-value pairs

Within my function, I am attempting to return a set of key-value pairs upon promise completion, but encountering difficulties. const getCartSummary = async(order) => { return new Promise(async(request, resolve) => { try { cons ...

What is the best way to retrieve JavaScript variable data from a GDownloadUrl callback function?

Recently, I attempted to extract data by crawling a website. The website in question offers real-time information on bicycle stations through Google Maps. GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) { var jso ...

Focus on the image displayed through instafeed.js

Using the Instafeed.js plugin to create a dynamic Instagram feed. Everything is working smoothly, but I'm struggling to center the images being retrieved by Instafeed. Despite trying various methods, I can't seem to get it to display as desired. ...

Java: Finding the largest possible sum along a path within a two-dimensional array

So, here's the situation I'm dealing with: In a 2D square array representing a garden of strawberry plants, each plant (each element) has a specific number of strawberries. Starting at the top left corner of the array, you can only move to the r ...

React JS implementation of Dropbox logic with multiple steps

Greetings to you and your loved ones. I am in need of your assistance with a minor issue that has been eluding me for the past three days. I have been utilizing a basic React library for the following scenario: Scenario I have set up 4 dropdown menus: I ...

Retrieve JSON information using PHP and JavaScript SDK exclusivley

After successfully setting up the Facebook Javascript SDK and getting it to display the right information on the page, I have also managed to echo the user into the Firebug console to show the Object containing all of the user profile details. * I am opti ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

Change the function to utilize an HTML class rather than an ID

I am currently working on a resize image function that requires the ID of a file input element as an input. The function takes the image in the form and outputs a resized canvas of the image. However, I recently made changes to the form structure from a st ...

Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using: <h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1> Below is my dialog ...

Working with jQuery.ajax Function Calls in Array Filter Operations with Javascript

My knowledge of AJAX calls is limited, so I am unsure about how they interact with array filtering using A.filter(). The array in question is used to populate a template synchronously. // An event triggers a function to filter a list on the page. // The f ...

Update the state both before and after executing the API call

I'm facing an issue with the setState function where it seems to be getting called again before completing the previous batch of state updates. My data object has the following structure: [{ id: 0, loading: false }] On my webpage, I have toggle butt ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...