What is the best way to calculate the total sum of multiple arrays inside an array of objects?

I need help figuring out how to calculate the sum of multiple arrays within an array of objects. Here's the code I have:

const employeeList = [    

    {
        "name": "Ahmed",
        "scores": [
            "5",
            "1",
            "4",
            "4",
            "5",
            "1",
            "2",
            "5",
            "4",
            "1"
        ]
    },
    {
        "name": "Jacob Deming",
        "scores": [
            "4",
            "2",
            "5",
            "1",
            "3",
            "2",
            "2",
            "1",
            "3",
            "2"
        ]
    }];

var sum = 0;

for(let i = 0; i < employeeList.length; i++){
    var eachScore = employeeList[i].scores;
    const b = eachScore.map(Number);
    console.log(b);

    sum += parseInt(b);//this is the code that doesn't work

}

console.log(sum);

I'm able to display the arrays in the console, but I can't seem to figure out how to properly sum up the values in each array. Using parseInt with concatenate or simply give me the length of the array instead of the sum. I think using the .split() method could help split the arrays and sum them individually, but I haven't quite nailed down the implementation yet.

Answer №1

Since b represents an array of numbers, using the + operator with it will result in a comma-joined string rather than a proper sum. The best approach to summing up an array is by utilizing the reduce method, which allows for iterating over the elements and adding them to an accumulator:

b.reduce((a, b) => a + b);

If you are interested in calculating partial sums, one way could be to use .map to convert each object in the employeeList array into the total sum of their scores. This can be achieved by extracting the scores property and applying the reduce function to add them all together:

const employeeList=[{"name":"Ahmed","scores":["5","1","4","4","5","1","2","5","4","1"]},{"name":"Jacob Deming","scores":["4","2","5","1","3","2","2","1","3","2"]}]
const sum = (a, b) => Number(a) + Number(b);
const output = employeeList.map(({ scores }) => scores.reduce(sum));
console.log(output);
// To calculate the sum of all results:
console.log(output.reduce(sum));

Answer №2

To find the total sum, you can utilize array reduce method:

const employeeList = [    
{
  "name": "Ahmed",
  "scores": [
  "5",
  "1",
  "4",
  "4",
  "5",
  "1",
  "2",
  "5",
  "4",
  "1"
  ]
},
{
  "name": "Jacob Deming",
  "scores": [
  "4",
  "2",
  "5",
  "1",
  "3",
  "2",
  "2",
  "1",
  "3",
  "2"
  ]
}];

var sum = 0;

for(let i = 0; i < employeeList.length; i++){
  let eachScore = employeeList[i].scores;
  let b = eachScore.reduce((total,current)=>{
    total += +current;
    return total;
  },0);
  console.log(b);

  sum += b;
}

console.log(sum);

Answer №3

Here is a helpful solution:

let parsedNumbers = [];
let numbers = [
   "7", "9", "4", "6", "1", "8", "5"
];
let sum = 0;
numbers.forEach(num => {
   parsedNumbers.push(parseInt(num))
})
for (let num in parsedNumbers) {
   sum += parsedNumbers[num]
}
console.log(sum);

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

Tips on passing a JSON object from JavaScript to ASP.NET

I attempted to invoke a method in an asp.net controller using a json string/object from javascript. The asp.net controller code is as follows: public class HomeController : Controller { public ActionResult doWork(string data) { // dowork. ...

Contrasting approaches for generating a character array

I've always been interested in the various ways to create a character array in C. For example, if we want to store the string "John Smith" in an array, there are multiple approaches. One way is to initialize the array with the exact number of elements ...

Send information back to the initial website following a sequence of alternating requests

I am facing a challenge with my website's structure: On the "Client side", I have HTML / CSS / JavaScript, and on the "Server side", I have PHP. When a user interacts with the client side by clicking a button, they are redirected to a page where a s ...

The URL http://localhost:3001/users/signup returned a 404 error, indicating that the page was

Hello, I've been working on setting up my user routes using Sequelize for MySQL. However, when I try to test my requests by sending them to http://localhost:3001 via Postman, I'm receiving a 404 (Not Found) error for http://localhost:3001/users/s ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

The script encountered an error when attempting to access the property 'getContext' of a null object during the page's

window.onload = function() { var ctx = document.getElementById('chart-area').getContext('2d'); window.myDoughnut = new Chart(ctx, config); }; Upon loading the window, an issue occurred where the chart function was not working a ...

How can a multidimensional array containing two nested arrays be sorted?

My objective is to organize an array based on values specified in another array. Here is the array in question: Array ( [0] => Array ( [0] => 13.31421 [1] => WP_Post Object (...) ) [1] => Array ...

Generate a series of rotations ranging from -60 to 60 using d3.cloud

I need help replicating the word cloud feature found on for my website. After studying examples and referencing a Stack Overflow answer, I put together the following code: var fill = d3.scale.category20(); var layout = d3.layout.cloud() .size([900, ...

ResponseEntity in Spring Boot is a powerful feature that allows

When retrieving all products from Spring Boot, the key names are being converted to lowercase instead of returning with their original values. [{"pname":"Mobile","pquantity":52,"pid":1,"pprice":2000}] My e ...

Getting state from two child components in React can be achieved by using props to pass the

In my tabbed modal dialog, I have two image list components rendering images based on props defined in the parent. Each component manages its own array of image objects. The challenge is that I need to update or delete these images using a single save butt ...

Expanding the size of an array

Trying to figure out how to resize an image by half using arrays has me stumped. The function provided is: public static int[][] resizeImage(int[][] original, int newWd, int newHt) The task is to use 2D arrays to transfer pixels from the original image t ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

The data store is completely barren even though I received a response from the server

Below is the model definition: Ext.define('DynTabBar.model.Menu',{ extend: 'Ext.data.Model', config: { fields: [{ name: 'Title', type: 'string' ...

Generate a new item using an existing one

I am seeking to extract the desired output from the provided input: Input Configuration: var inputParams = { 'inputDetails' :[ { 'field' : 'specificationName', 'value' : 'strong'}, { ...

Can anyone provide step-by-step guidance for integrating Bootstrap 5.3 popovers into a Rails 7 esbuild application?

When setting up a brand new Rails 7 app with Bootstrap, I noticed that Modals work seamlessly, but Popovers lack the same functionality. How can I make Popovers work? Rails 7.1.2, esbuild, Bootstrap 5.3.2: rails new --database sqlite3 --javascript esbuild ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Eliminate redundant elements

In my TypeScript code, I am working with an array of objects that looks like this: [ {target_col: "`qsze`", operation: "", isNew: false, operationNotCompiled: "", index: 25}, {target_col: "`qsf`", operation: "", isNew: false, operationNotCompiled: "", ...

Use Google Sheets to automatically generate a text string in column C whenever a value is present in both column A and column B on the same row

Just like the title states, I am dealing with two columns of data. If the second column contains any data that is an exact match to the first column, I need the third column to output the string "found" on the same line as the data in the first column. Ch ...

Jenkins is experiencing issues with starting up or reconnecting - It is hanging and displaying a severe error message: unable to properly read the JSON file provided at [/var/lib/jenkins/cb-envelope/envelope.json]

Jenkins: Version 2.89.4-x rolling Encountered slow performance issues with Jenkins due to memory problems. After trying to restart Jenkins using the sudo or usual method, a severe issue was encountered. Eventually, restarted the entire Jenkins machine in ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...