0

In C#, we have a .Sum(Predicate) method that lets you use a lambda expression to do a summation over a collection of objects. For instance, if I had the following set of objects (using JSON for simplicity)

[
  {
    "Id": 1,
    "Sub": {
      "Size": 1
    }
  },
  {
    "Id": 2,
    "Sub": {
      "Size": 3
    }
  }
]

And I wanted to get the sum of the sizes, I could do Sum(n => n.Sub.Size)

Is there a way to do something like this in javascript? I am really new (and weak) at the language and am having trouble performing a similar function. I am using jQuery, so I am open to that opening anything too.

3 Answers 3

3
var result = arr.reduce(function(a, b) {
    return a + b.Sub.Size;
}, 0);

Demo: http://jsfiddle.net/sUCTK/

Documentation: MDN

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

3 Comments

Note this is not available in some browsers (we all know which).
@jbabey: yep :-) And for them there is a shim function on the documentation page available
@Ciel: open MDN page and scroll down to Compatibility section. The implementation below the title is it. "Shim" is a common name for an implementation for old browsers that don't support required function/feature yet.
0

In JavaScript you'll need to manually step through the array and add up the values:

var sum = 0;
for (var i in a) {
  sum += a[i].Sub.Size
}
// sum now contains the total

1 Comment

I would avoid using in to traverse an array. in is for enumeration, not iteration. If we prototyped Array with a new member, I think you'd traverse that member.
0

For cross-browser compatibility, you could do this:

var sum = function(arr, callback, initial_value) {
    if (arguments.length < 3) {
        initial_value = 0;
    }
    var ret = initial_value;

    for (var i = 0; i < arr.length; i++) {
        ret += callback(arr[i]);
    }        

    return ret;    
};

console.log(sum(arr, function(element) {
    return element.Sub.Size;
});

This would also let you sum other summable objects, like strings, by passing the appropriate-type initial_value.

@zerkms shows how to use new ECMAScript standards to better sum things.

3 Comments

Hm... What is the use of sending a null as third parameter to use as initial value?
@Guffa That's how I learned to send optional parameters. In retrospect, there actually is an arguments.length that I've forgotten about — I'll change it.
Now it makes more sense. I think that you got the condition backwards, as it changed anything that wasn't null to 0, i.e. if you sent "" it would change it to 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.