1

I want to sum over the number of calls in my array 'data'. I've found the 'reduce' function, but don't know how to select the calls part of the array. Here's my attempt at doing it:

data = {
        links: [
                  {source: 0,target: 1, calls: 20, texts:0},
                  {source: 0,target: 2, calls: 5, texts:0},
                  {source: 0,target: 3, calls: 8, texts:0},
                  {source: 0,target: 4, calls: 3, texts:0},
                  {source: 0,target: 5, calls: 2, texts:0},
                  {source: 0,target: 6, calls: 3, texts:0},
                  {source: 0,target: 7, calls: 5, texts:0},
                  {source: 0,target: 8, calls: 2, texts:0}
                ]
        }

var total_calls = data.links.calls.reduce(function(a, b) {
  return a + b;
});
0

2 Answers 2

3

You need to iterate over the data.links array, like this

var total_calls = data.links.reduce(function(result, currentObject) {
  return result + currentObject.calls;
}, 0);
console.log(total_calls);
// 48
Sign up to request clarification or add additional context in comments.

Comments

1

How about making this a little bit more reusable?

data = {
        links: [
                  {source: 0,target: 1, calls: 20, texts:0},
                  {source: 0,target: 2, calls: 5, texts:0},
                  {source: 0,target: 3, calls: 8, texts:0},
                  {source: 0,target: 4, calls: 3, texts:0},
                  {source: 0,target: 5, calls: 2, texts:0},
                  {source: 0,target: 6, calls: 3, texts:0},
                  {source: 0,target: 7, calls: 5, texts:0},
                  {source: 0,target: 8, calls: 2, texts:0}
                ]
        }

pluck = function(ary, prop) {
  return ary.map(function(x) { return x[prop] });
}

sum = function(ary) {
  return ary.reduce(function(a, b) { return a + b }, 0);
}

result = sum(pluck(data.links, 'calls'))
document.write(result)

1 Comment

Both solutions are quite nice, but for my purposes it's actually perfect that's reusable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.