javascriptarraysobjectarray.prototype.map

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.

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);