JavaScript Sum Array and Array Of Object

JavaScript sum of array and object; Through this tutorial, i am going to show you how calculate sum of array values and sum array of objects by key using for loop, map, and reduce() method

JavaScript Sum Array and Array Of Object

Use the following ways and method to calculate sum array of objects by key in javaScript; As shown below:

  • Sum of Array in JavaScript
  • Sum of Array javaScript Reduce
  • JavaScript Sum Array Values using Map() method
  • JavaScript Sum of Array of Objects
  • JavaScript Sum of Array of Objects Reduce

Sum of Array in JavaScript

Let’s see the following example for sum of array in javascript using for loop; as shown below:

var numArr = [10, 20, 30, 40] // sums to value = 100
var sum = 0;
for (var i = 0; i < numArr.length; i++) {
  sum += numArr[i]
}
document.write( "javascript- Sum of the array value is :- " + sum ); 

Result of the above code is :- 100

Sum of Array javaScript Reduce

To calculate sum of array using reduce() method in javaScript; as shown below:

    var numArr = [10, 20, 30, 40] // sums to value = 100
    var sum = numArr.reduce(function(a, b){return a+b;})
    document.write( "javascript- Sum of the array value is :- " + sum ); 

Result of the above code is: 150

JavaScript Sum Array Values using Map() method

To find sum of array values using map() method in javaScript; as shown below:

   var numArr = [10, 20, 30, 40] // sums to value = 100
   var sum = 0;
   numArr.map(function(x){sum+=x})
   document.write( "javascript- Sum of the array value is :- " + sum ); 

Result of the above code is:- 105

JavaScript Sum of Array of Objects

To find sum array of objects by key using for loop in JavaScript; as shown below:

    var numArr = [
        {  name: 'a', num: 50},
        {  name: 'b', num: 50},
        {  name: 'c', num: 75},
        {  name: 'd', num: 35},
        {  name: 'e', num: 25 },
    ];
    var sum = 0;
    for (var i = 0; i < numArr.length; i++) {
      sum += numArr[i].num
    }
    document.write( "javascript- Sum of the array value is :- " + sum ); 

JavaScript Sum of Array of Objects Reduce

Using javaScript reduce() method, you can find sum array of objects by key; as shown below:

    var numArr = [
        {  name: 'a', num: 50},
        {  name: 'b', num: 50},
        {  name: 'c', num: 75},
        {  name: 'd', num: 35},
        {  name: 'e', num: 25 },
        {  name: 'f', num: 40 },
    ];
    var sum = numArr.reduce(function (total, currentValue) {
        return total + currentValue.num;
    }, 0);
    document.write( "javascript- Sum of the array value is :- " + sum ); 

Result of the above code is:- 275

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published.