1

I have an array of javascript objects:

var myObjects = [{figure: 3}, {figure: 5}, {figure: 2}];

I would like code that could give me a total of 10 based on the addition of all figure properties of objects in myObjects.

What I've Tried/Done

I could loop through using jQuery's .each() but I don't feel like iterating (and using a temporary 'store' variable) is the most elegant.

Obviously I could also do:

myObjects[0] + myObjects[1] etc. - but assume there is an arbitrary amount of objects.

I've done something similar for getting the minimum already:

var lowest = Math.min.apply(null, myObjects.map(function (x) { return x['figure']; }));

But would like the equivalent for total.

0

1 Answer 1

2

You could use Array.prototype.reduce:

var data = [{figure: 3}, {figure: 5}, {figure: 2}],
    sum = data.reduce(function(memo, c) { return memo + c.figure }, 0);

reduce is part of ECMAScript 5, so it is available in IE9+ and recent versions of all other browsers - see this compatibility table.

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

5 Comments

Why the downvote? Thanks a lot joews - will look into using reduce (never heard of it).
Please don't downvote without providing comments. It doesn't help anybody and, as it happens, this answer (and the other current answer) are correct.
+1 for answer... I think I'm needlessly trying to avoid temporary variable here aren't I.
I think this solution is much cleaner than an explicit loop. Surely an accumulation variable (memo in this case) is required to perform any kind of iterative summation?
I think you're right, there's no need for me to optimise it further. Sorted.

Your Answer

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