Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map through an array of objects and add the total in each object to a variable in Javascript

Here is an array of objects

const items = [{description: "Cement", total: "150"}, {description: "Mortar", total: "200"}, {description: "Sand", total: "100"}]

I want to add the total of each object to a variable so that i can get the grand total of everything.

I have tried mapping through the items array and then for each item.total i added it to a variable but it does not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

items.map((item) => {
          let sum = 0
          sum += item.total
})

Any help would be much appreciated. Thanks.

>Solution :

Your code is not working, because you initialize a new variable inside a loop in each iteration. In your example the sum variable should be in a global scope. Moreover you should convert strings to numbers to sum them. Here is fixed version of your code:

const items = [{description: "Cement", total: "150"}, {description: "Mortar", total: "200"}, {description: "Sand", total: "100"}];

let sum = 0;

items.map((item) => {
  sum += Number(item.total);
});

console.log(sum);

However in such cases when you want to accumulate array values to a single value, it’s better to use reduce method:

const items = [{description: "Cement", total: "150"}, {description: "Mortar", total: "200"}, {description: "Sand", total: "100"}];

const sum= items.reduce((acc, item) => acc + Number(item.total), 0);


console.log(sum); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading