How can I sum up each array elements using a forEach loop in JavaScript?

Check out my code snippet:

var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = [];
data.forEach(function(entries) {
    entries.reduce(function(a, b) {
        return a + b[1];
    }, 0);
    console.log(entries);
});

I want to sum the numbers in each array together.

I'm not sure how to achieve this within the forEach loop?

Instead of individual arrays, I'm aiming for the output: [120, 60, 165].

The goal is to extract the combined totals from nested arrays into a single line.

Looking forward to any advice or suggestions!

Thank you!

Answer №1

It is recommended to use the Array#map method instead

Keep in mind that b[1] may hold a value of undefined, and when using entries.reduce, it returns a reduced value which you can either return or store in a variable

var data = [
  [40, 20, 60],
  [20, 30, 10],
  [50, 75, 40]
];
var averageData = data.map(function(entries) {
  return entries.reduce(function(a, b) {
    return a + b;
  }, 0);
});

console.log(averageData)

Edit- To improve readability as suggested by @Tushar in the comments, here is an alternative in ES6 version:

var data = [
  [40, 20, 60],
  [20, 30, 10],
  [50, 75, 40]
];
console.log(data.map(arr => arr.reduce((a, b) => a + b, 0)));

Answer №2

By using the reduce() function, you can achieve the desired sum result. Check out the example below.

var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = []
data.forEach(function(entries) {

    var sum = entries.reduce(function(a, b) {
      return a + b;
    }, 0)
    console.log(sum)

})

Answer №3

If you are confident that your values are secure (meaning you are aware of their source), one option is to utilize the eval function to rapidly calculate the sum of the values.

var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var totals = [];

data.forEach(function(a, i) {
  totals.push(eval(a.join('+')));
});

console.log(totals);

While not the most efficient method, it can still get the job done.

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

What is the method for determining the dimensions of the rectangle that the camera can capture at a specific location?

In my latest project, I developed a small three.js application that showcases the movement of multiple circles from the bottom to the top of the canvas: let renderer, scene, light, circles, camera; initialize(); animate(); function initialize() { re ...

Determining the state update value in useEffect using dispatch and payload in Redux

Apologies for the confusion in the title. I am currently working with React and Redux-toolkit. I encountered an issue where when referencing the updated value in the useState set function, I ended up getting the value before the update. I understand that ...

Update the pageExtensions setting in Next.js to exclude building pages with the file extension *.dev.*

I am currently working on a project using Next.js version v12.3, and I have encountered an issue related to excluding page files with a *.dev.* extension from the build process. In my configuration file next.config.js, I have configured the pageExtensions ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Identify Horizontal Swipe Gestures on Page-level

I am currently focused on ensuring accessibility for users utilizing voiceover technology. While navigating their phone, these individuals rely on right and left swipes to interact with elements on a page. I am seeking to implement swipe detection at the ...

Encountering a RangeError when transmitting OpenLayers3 event via AJAX

An error is appearing in the chrome console stating: RangeError: Maximum call stack size exceeded The code I am using is as follows: draw.on('drawend', function(evt) { var fe = evt.feature console.log(fe); ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...

Exploring ways to create simulated content overflow using react-testing-library

I have integrated material-table with material ui to develop a spreadsheet application. One of the features I have added is setting a maximum width of 50px for cells. If the content in a cell exceeds this width, it will display an ellipsis at the end of ...

Extract the data that was returned from the AJAX post function

I am looking to create a condition that is dependent on the data received from an ajax post outside of the post function function post(){ $.post('page.php',$('#form').serialize(), function(data) { if(data !== 'good'){a ...

Display the number in a formatted manner without displaying any zeros in the decimal part

Can you help me with a decimal number display issue I am having? <nested:text property="product.price" maxlength="5" onclick="javascript:validatePriceValue(this);"/> number displayed as 44 44.00 I want to use J ...

Generating references dynamically without the use of strings

UPDATE: Our current React version is 16.2.0, which is important for this question (check out this answer). From what I understand, this is the recommended way to create a ref in our React version: <div ref={(r) => { this.theRef = r; }}>Hello!< ...

Is there a Page Views tracker in sinatra?

Help needed with implementing a page views counter using Sinatra and Ruby. I attempted using the @@ variables, but they keep resetting to zero every time the page is reloaded... Here's an example: Appreciate any advice! ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

React filtering displaying array elements that appear single time

I've been working on this React code to filter and search items based on user input. The issue I'm facing is that when I delete the text input and try again, the filtered items disappear and don't show up unless I reload the page. I'm c ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...

sending ajax information to create a pie chart displaying data percentages

I am currently facing confusion on how to pass or assign a value of my data-percent pie chart through my ajax data retrieved from the database. While I have successfully passed other fields using an id, I am stuck on how to incorporate the value for data p ...

substitute a component with a different one if it is present

I'm currently working on a script that will automatically replace one element with another as soon as it is created, even when the page loads. Despite my attempts to use MutationObserver, I haven't been successful. var target = document.querySe ...