Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I'm trying to write a function that sums all the items in any array. For instance, I have an array [1,2,3] = 6.

function sumArray(arr) { for (i = 0; i = arr.length; i++) { } return sum; }

This what I have so far. Thanks in advance!

2 Answers

Steven Parker
Steven Parker
243,318 Points

You've established a loop, and you return the final sum, so far so good.

Now you just need to declare sum before the loop, and inside the loop increment it by the current array value.

If you need a few more hints:

  • when you declare sum, remember to also set it to 0.
  • your index is i, so the current array value inside the loop will be arr[i]
  • the "increment by" operator is +=

I'll bet you can get it now without an explicit spoiler.

Thank you Steven! I think this works:

function sumArray(arr) { var sum = 0; for (var i = 0; i < arr.length; i++){ sum = sum + arr[i]; } return sum; } sumArray([1,2,3]);

JS provides a .reduce() method on the Array prototype that should do this perfectly for you.

function reduceMe(arrayOfNumbers) {
  return arrayOfNumbers.reduce(function(x, y) {
    return x + y;
  });
}

console.log(reduceMe([1, 2, 3])); // 6

In short, what .reduce() does is you pass it a function with (at least) 2 arguments, which it takes as the sequential values in the specified array, performing the function statements and taking the returned value, which it then uses in the function again as the first argument (x), and taking the next value in the array for (y) until it is completely out of array elements.

So here, its first action is 1 + 2, returns 3, then 3 + 3, returns 6.