4

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?

0

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

3

just write follwing code after your original code

var result = result.reduce(add, 0);

function add(a, b) {
    return a + b;
}

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.