What is the process for determining the total of elements within an array?

Imagine you have the following array:

const items = [
  {
    "amount1": "100",
    "amount2": "50",
    "name": "ruud"
  },
  {
    "amount1": "40",
    "amount2": "60",
    "name": "ted"
  }
]

Your goal is to calculate the sum of all amount1 and amount2 properties, resulting in:

[
  {
    "amount1": 140,
    "amount2": 110
  }
]

How would you go about achieving this?

Answer №1

Utilizing Array.prototype.reduce() in combination with Object.entries() and Array.prototype.forEach():

const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];

const sums = items.reduce((acc, item) => {
  Object.entries(item).forEach(([k, v]) => acc[k] = (acc[k] || 0) + v);
  return acc;
}, {});

console.log(sums);

To eliminate non-numeric properties (while preserving quoted number strings, based on the updated query):

const items = [{amount1: '100', amount2: '50', name: 'Ruud'}, {amount1: '40', amount2: '60', name: 'Ted'}];

const sums = items.reduce((acc, item) => {
  Object.entries(item)
        .filter(([_, v]) => !isNaN(v))
        .forEach(([k, v]) => acc[k] = (acc[k] || 0) + Number(v));
  return acc;
}, {});

console.log(sums);

Answer №2

const numbers = [{num1: 100, num2: 50}, {num1: 40, num2: 60}];
function calculateTotal(data){
 const keys =  Object.keys(data[0])
 let result = {}
 for(key of keys)
   result[key]=data.map(x=>x[key]).reduce((a,b)=>a+b);
return result
  
}

console.log(calculateTotal(numbers))

Answer №3

Here's a quick and efficient solution to tackle this problem.

const data = [{num1:100, num2:50, title:"John"},{num1:40,num2:60,title:"Jane"}]
let total = [{num1:0,num2:0}]
data.forEach(item=>{
  total[0].num1 += item.num1
  total[0].num2 += item.num2
})
console.log(total)

Answer №4

Below is an alternative approach that does not rely on Array.prototype.reduce(). This solution accommodates scenarios where there are properties in the array items that are not strictly "numbers".

 const elements = [{quantity: 10, weight: 5, product: 'Apple'}, {quantity: 4, weight: 6, product: 'Banana'}];
 var finalResult = {};

 elements.forEach(function(element){
    for(var key in element){
        if(typeof element[key] === "number"){
           finalResult[key] = finalResult[key] ? finalResult[key] + element[key] : element[key];                 
        }                
     }
 });
 finalResult = [finalResult];
 console.log(finalResult);

Answer №5

If you are looking to consolidate the numeric values in an array of objects, one effective approach is to utilize the reduce() method.

  • To implement this solution:
  • Apply the reduce() method on the target array, which we've referred to as items.
  • Define the accumulator (ac) as an empty object - {}.
  • Within each iteration over the objects, use a for..in loop to cycle through all keys within the object.
  • Verify whether the typeof value for the current key is a number; if so, include it in the accumulation.

const items = [{amount1:100, amount2:50, name:"ruud"}, {amount1:40,amount2:60,name:"ted"}]

let res = [items.reduce((ac,x) => {
  for(let key in x){
    if(typeof x[key] === "number"){
      if(!ac[key]) ac[key] = 0;
      ac[key] += x[key]
    }
  }
  return ac;

},{})]
console.log(res)

Answer №6

reduce() is definitely the best approach, but a more elegant way to handle only specific keys is by using the expected result as the accumulator and iterating over its keys:

const items = [
  { amount1: "100", amount2: "50", name: "ruud", foo: "unrelated" },
  { amount1: "40", amount2: "60", name: "ted", foo: "0" }
];

const result = items.reduce((acc, item) => {
  for (let key in acc) { // loop through the keys of the accumulator
    acc[key] += isNaN(item[key]) ? 0 : +item[key];
  }
  return acc;
}, { // defining the expected format here
  amount1: 0,
  amount2: 0
});

console.log(result);

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

Combining the Powers of ExpressJS and MeteorJS

I am currently using an Epress JS rest api to send data to a MongoDB database. I'm curious if it's feasible to incorporate Meteor JS for fetching these values from the MongoDB. Any insights or suggestions would be greatly valued. Thank you ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Is it possible to include a callback function as a property in an object in React?

I need to include a callback function in a prop of type object. I have developed a custom component for a data table where I pass columns, data, and actions as props. The actions prop consists of an array of objects with handler callback functions linked ...

Unable to retrieve input value from dynamically-generated field with JQuery

There seems to be an issue with receiving a value from a static field when using the keyup method based on the input field class (.inputclass). Once a field is added dynamically, it does not get the value. Below is a sample code. Any help would be appreci ...

Angularjs still facing the routing issue with the hashtag symbol '#' in the URL

I have recently made changes to my index.html file and updated $locationProvider in my app.js. After clicking on the button, I noticed that it correctly routes me to localhost:20498/register. However, when manually entering this URL, I still encounter a 4 ...

Convergence phenomenon in SVG when two distinct paths intersect

Working with individual SVG paths and in need of a mitre effect when there is a path join, which is a new concept for me. The SVG shape resembles a polygon, with each side as its own individual path. Although the sample SVG code provided does not display ...

Looking to create a GitHub example in Fiddle but running into issues with getting the result?

I've been working on an example on Fiddle, but it's not functioning as expected. I want to implement i18next so that the text changes when the user switches languages. After searching for a solution, I came across this GitHub repository: https:// ...

To access a form element in JavaScript function, utilize the dynamic form name approach

Currently, I am facing an issue with a JavaScript alert function where I am trying to view the HTML form URL before it is submitted. Following advice from a post on StackOverflow about retrieving form submit content before submit, I attempted to implement ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Console frozen when executing an async JavaScript script to populate a Mongoose database

I'm currently delving into a personal project and aiming to unravel the intricate logic that is preventing my Node JS process from closing after executing populateTransactions(). My assumption is that the issue lies in not properly closing the DB con ...

transform pixel coordinates to latitude and longitude dimensions

Seeking clarification on how the geo referencing process functions for images. Is there a method to accurately extract latitude and longitude information from this specific line of code? imageBounds = [map.unproject([0, 0], 20), map.unproject([1716,1178], ...

Error in THREE.js: Unable to access property 'lib' from an undefined source (THREE.ShaderUtils.lib["normal"])

I have been working on the challenges provided in the WebGL introductory book by Oreilly. Encountered a runtime error with the following code snippet. After searching online, it seems like I am the only one facing this issue. Could you please assist me in ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Ensuring the server application is up and running before initiating the mocha tests

This is similar to Ensuring Express App is running before each Mocha Test , but the proposed solution isn't effective + I am utilizing a websocket server In essence, I'm making use of a websocket framework called socketcluster and this represent ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...