Skip to content

JavaScript reduce array of objects sum | Example code

  • by

The reduce method executes the call-back function multiple times. For each time, it takes the current value of the item in the array and the sum array of objects in JavaScript.

JavaScript reduce array of objects sum

A simple example code gets the sum of msgCount prop across all objects in the array.

<!DOCTYPE html>
<html>
<body>

  <script>
    var accounts = [
    { name: 'James Brown', msgCount: 40 },
    { name: 'Jemes Wonder', msgCount: 50 },
    { name: 'Kim Stone', msgCount: 10 },
    { name: 'Tim Steve', msgCount: 300 }  
    ];


    var msgTotal = accounts.reduce(function(prev, cur) {
      return prev + cur.msgCount;
    }, 0);

    console.log('Total Messages:', msgTotal);

  </script>

</body>
</html> 

Output:

JavaScript reduce array of objects sum

More example

var arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
  return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Do comment if you have any doubts or suggestions on this JS reduce topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *