JavaScript code to calculate the total of elements in a multi-dimensional array

I am working on a JavaScript project where I need to calculate the sum of each subarray using forEach, map, and reduce functions. My goal is to have an output like this:

sum = [8, 13, 22]

However, despite my efforts, I cannot seem to get the desired outcome. Can someone please help me figure out where I am making a mistake? Thank you.

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) { 
  item = item.reduce(function(a, b) {
    return a + b;
  });
  newArr.push([item]);
});
console.log(newArr);

Answer №1

You have the option to calculate the totals of each object's values.

var data = [{ a: 1, b: 2, c: 5 }, { a: 3, b: 4, c: 6 }, { a: 6, b: 7, c: 9 }],
    result = data.map(obj => Object.values(obj).reduce((acc, val) => acc + val));

console.log(result);


Here are some notes on the provided code:

Remember that you cannot directly iterate over an object using reduce, as it is designed for arrays. To overcome this, extract the object values using Object.values and then perform the iteration.

Return the sum without wrapping it in an array.

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) { 
    var sum = Object.values(item).reduce(function(acc, val) {
        return acc + val;
    });
    newArr.push(sum);
});

console.log(newArr);

A more efficient approach would be utilizing Array#map, especially when you require one value per array element.

var data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
    newArr = data.map(function(item) { 
        return Object.values(item).reduce(function(a, b) {
            return a + b;
        });
    });

console.log(newArr);

Answer №2

Looking at the given example, it appears to be the traditional approach

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(object) {
  let sum = 0;
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
        sum += object[property]
    }
 }
  newArr.push(sum);
});
console.log(newArr);

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

JavaScript Regular Expression for standardizing phone number input

I'm working with an input for a phone number in French format which can accept two different formats: 0699999999 +33699999999 There is currently no check for the length of the number. In the database table, the field is varchar 12, but shorter inp ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

Using Scanf in C to Handle Multiple Conditions

TLDR: Checking if scanned input into an array is an integer while using EOF. I am trying to scan numbers into an array until EOF using statically allocated memory. I am still a beginner and dynamically allocated memory is difficult for me to grasp at the ...

Tips for changing an input value when clicked using JQuery

Struggling to create an interactive mind mapping tool using JQuery? One challenge I'm facing is editing the content of a div once it's been set. I've implemented a function that successfully adds text to a div within the (mind-container). H ...

Vuejs tab not displaying images

I have created a method called "numberMatch" that adds a gif, stored in a variable, to a tab when clicked. The method is functioning correctly, but when I try to display the gif on the page by calling the tab in the template, it only shows the path of th ...

Displaying the unique values based on the key attribute

I'm developing a category filter and struggling to showcase the duplicate options. Within my array of objects: filterData = [ { name: 'Aang', bender: 'yes', nation: 'Air', person: 'yes', show: 'ATLA&apo ...

Simply close by clicking outside using basic vanilla JavaScript

I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area. Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only b ...

Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for. var startTimestamp = 1488021704531; var endTimestamp = 1488022516572; I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Strategies for resolving the problem of null values from getParameter() being passed from AJAX to servlet

After reading numerous answers on Stack overflow, I have tried various solutions to fix this issue without success. My goal is to send a JavaScript variable to a servlet using AJAX within an else statement in JS. However, I keep receiving null in the alert ...

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: https://i.sstatic.net/ILdsl.png This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to id ...

A solo-dimensional array generated within a PHP while loop

Is there a way to extract the value of an array that is enclosed within a while loop and then use it outside of the loop? I managed to achieve this using the following code: $xyz = array(); while($row2 = mysql_fetch_assoc($result2)) { $value = $row2[& ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...

Ensuring a button (class) is in active hover mode when the document loads

My website features 4 clickable service buttons on the homepage, each with a unique hover effect (background-color change) when users interact with them. While this setup works well overall, I am looking to highlight the FIRST button as the most important ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

Switch up the URL and redirect by employing jQuery

Looking for a solution in jQuery to redirect based on user input? <form id="abc"> <input type="text" id="txt" /> </form> If you want to redirect to a URL constructed from the value of the text box, you can try this: var temp = $("#tx ...

Exploring Array Iteration and Incrementing with Easing Techniques

I am currently working on a function that involves iterating over an array and incrementing the values by varying amounts. The challenge is to decrease these incremental amounts as the values in the array get larger. Let's consider the following exam ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

How to implement a self-invoking function in React JS like you would in regular JavaScript?

Is it possible to invoke the function good without triggering it from an event? I want it to run as soon as the page loads, similar to a self-invoking JavaScript function. Check out this example import React from 'react'; class App extends Reac ...