Loop through a collection of objects and combine their values

I'm struggling with what seems like a basic issue. I have an array that looks like this:

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];

I need to create a loop to add up all the values for 'a', 'b', and 'c' in each object of the array. The challenge is that I don't know how many objects will be in the array beforehand.

For example, instead of manually adding up the values like this:

var A = myArray[0].a + myArray[1].a + myArray[2].a;

Answer №1

You can utilize the reduce() function to calculate and return the result for each key in separate variables.

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var A = myArray.reduce(function(r, e) {
  return r + e.a;
}, 0)

console.log(A)

Alternatively, you can employ both reduce() and Object.keys() to compute the sum for each property of the objects in a single variable.

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var result = myArray.reduce(function(r, e) {
  Object.keys(e).forEach(function(k) {
    r[k] = (r[k] || 0) + e[k];
  });
  return r;
})

console.log(result);

Answer №2

Perhaps this can be of assistance.

let totalA = 0, totalB = 0, totalC = 0;
myDataArray.forEach(function(item){
  if (item.hasOwnProperty("a") {totalA += item["a"];}
  if (item.hasOwnProperty("b") {totalB += item["b"];}
  if (item.hasOwnProperty("c") {totalC += item["c"];}
});

Answer №3

Consider using the forEach() method:

let numberArray = [{x:3, y:4, z:5}, {x:-1, y:3, z:5}, {x:0, y:-3, z:1}];
let totalX = 0;
numberArray.forEach(item => {totalX += item.x});
console.log(totalX); // Output: 2

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

Merging a pair of numerical files to create a sorted third file, encountering obstacles with file names and cin input

Here is the code snippet that's giving me trouble... http://pastebin.com/KjzArbcg ^ View full code //problem area - this line causes a Segmentation fault char *filename1 = "HW11F1.txt"; cin >> filename1; ifstream filestream1(filename1); The t ...

unable to receive the data transmitted by the socket.io client

I hit a roadblock while trying to follow the tutorial on socket.io. I'm currently stuck on emitting events. Previously, I successfully received the console logs for user connected and user disconnected. However, when it comes to emitting messages, I a ...

Is it possible to incorporate an existing svg from the page into another svg element?

Currently, I am facing a challenge where I am programmatically creating logos as svgs with d3. Now, I have an svg map and I want to incorporate these logos into it. I am wondering if there is a way, whether through d3 or another method, to transfer these ...

How to send two different types of data using jQuery/AJAX to a .php file? (Syntax)

I am completely new to the world of jQuery/AJAX and I could really use some guidance. Here is the code snippet in question: $(function () { $('.button').on('click', function (event) { event.preventDefault(); //prevents ...

Tips for organizing and sorting date data in a JSON datatable

I am working with two date input fields: <form id="refresh" method="post" action="income.php"> <input type="text" id="dari" name="dari" /> <input type="text" id="sampai" name="sampai" /> <button type="submit">Refresh</b ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

Utilizing React.js components for Parsing JSON Objects

As a beginner in reactjs, I am faced with the challenge of parsing JSON response fetched from an API in index.html and passing it to a component called Card.js as props. Despite being able to access the response in the console log, I am unable to render it ...

Discover the possibilities of implementing variable component titles in qwik!

My aim was to dynamically utilize either HTML <button> or <Link> from Qwik library based on the presence of the href prop. However, it seems that the link is not functioning as expected and clicking on it doesn't produce any result. import ...

AngularJs Filter for Excluding Duplicates by Comparing Two Key Values

My Collection contains two Keys in the AngularJs model below. $scope.Collection=[{id:1,name:"A"},{id:1,name:"B"},{id:1,name:"A"},{id:1,name:"C"},{id:2,name:"A"},{id:2,name:"C"},{id:2,name:"A"},{id:3,name:"D"}]; I am looking to eliminate duplicate rows wh ...

Automatically populating username and password fields

Is it possible to set up automatic username and password filling on my website for users who have saved their login information in their browser? I want the user to just hit enter to login. Some websites already have this feature enabled, but others requi ...

When the div alters the content

Is it possible to hide a div after another div changes its content with a button click? For example, when I click on the submit button, the <div id="dynamic">1</div> changes to <div id="dynamic">2</div>. Once it ...

Unexpected JSONP Parsing Issue Despite Correct JSON Data

I've implemented a Cross Domain AJAX request using JSONP, and it's working fine with CORS. However, I'm facing an issue with JSONP. I've checked other threads but couldn't find a solution for my case. Below is the code snippet: ...

Utilizing jQuery's then() method to display HTML and JSON outputs from printing operations

Currently, I am in the process of mastering jquery deferreds. When working with html on jsfiddle, I receive an object that contains two lines when printed within the then() statement: "success" and the html returned by the ajax request. For instance, upo ...

JavaScript: protecting data, revealing functionality

Looking to enhance my understanding of Javascript basics in order to delve into client-side frameworks like Knockout and Angular, as well as make headway in learning Node.js. I've selected a simple problem used in teaching C# and am now attempting to ...

Encountering a "Karma error: resource not discovered" while examining an AngularJS application

I'm attempting to run my AngularJS application in Netbeans IDE, and I believe I've set up the files correctly. However, an error is appearing when I try to test it by right-clicking on my project and selecting Test: Karma cannot start (incorrect ...

MERN Stack deployment to Heroku: Remote rejected - unable to push changes to master branch (pre-receive hook declined)

Just a heads up: I've successfully deployed using this method around 3 times in the past, but now it seems to be failing. Could there have been an update with Heroku that's causing this issue? Not entirely sure... I'm attempting to push my ...

Storing user input values into a MySQL database using PHP

Is there a way to add multiple fields to MySQL at once rather than being limited to the number of values set in a record? I have a script that creates inputs, but I want to be able to add more values to MySQL. For example: id,name,1,2,3. However, I would ...

What is the best way to position buttons at the bottom of a material ui list and checkboxes at the top of the list?

Struggling with my CSS skills while working on a React TODO app using Material-UI. I need help in displaying TODO items in a Material-UI list format - where the list should have a checkbox as the first item, the TODO text as the second item, and edit/delet ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...