Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum array from map result dynamically using javascript [duplicate]

Tags:

javascript

I am getting the array from multidimensional array using map. Below is my code

 var data = [{"name":"ramu","id":"719","gmail":"[email protected]","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"[email protected]","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"[email protected]","ph":2332233232,"points":25}]          
var result = data.map(function(arr, count) { 
  return arr.points;
});

Output is [36, 122, 25]. But i need the sum as 183?

like image 826
ramu Avatar asked Oct 15 '25 23:10

ramu


2 Answers

Use Array#reduce method to get the sum of the property.

var data = [{"name":"ramu","id":"719","gmail":"[email protected]","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"[email protected]","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"[email protected]","ph":2332233232,"points":25}]          


var result = data.reduce(function(tot, arr) { 
  // return the sum with previous value
  return tot + arr.points;

  // set initial value as 0
},0);

console.log(result);
like image 122
Pranav C Balan Avatar answered Oct 18 '25 13:10

Pranav C Balan


Use Array's reduce() like the following:

var data = [{"name":"ramu","id":"719","gmail":"[email protected]","ph":988989898,"points":36},
    {"name":"ravi","id":"445","gmail":"[email protected]","ph":4554545454,"points":122},
    {"name":"karthik","id":"866","gmail":"[email protected]","ph":2332233232,"points":25}];
  
var result = data.reduce((sum, item) => sum + item.points ,0);
console.log(result);
like image 45
Mamun Avatar answered Oct 18 '25 13:10

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!