Help with .reduce

I’ve had trouble with ‘condense arrays with .reduce’ in the ‘Object Oriented and Functional Programming’ section. I have finished the whole section but this one I cant seem to do. any help would be appreciated, thanks.

I love this tweet. It shows the 3 common functions used on arrays.

.map you should already know. It’s a 1 to 1 change. Each item in an array becomes something else and you should still have the same array length at the end.

.filter returns a given array item if a test statement is true. Items here don’t change, but not all items make it through to the next stage.

.reduce takes all the items in an array and tries to change them into a single item. If you had an array of numbers (like the challenge. wink, wink), you could get the sum total of all items without needing to know the length of the array. If you had a multidimensional array (an array of arrays), you could flatten it into an array of single items.

The magic of reduce is the accumulator. It’s like a running total of everything you’ve done so far. As reduce operates on each item in an array, it tries to add/subtract/concatenate/etc onto the accumulator. After it’s gone through all the items in the array, the accumulator is finally assigned to a variable.

Following the example we’re given:

var singleVal = array.reduce(function(previousVal, currentVal) {
  return previousVal - currentVal;
}, 0);

If array is [1,2,3,4], then after going through the above code, singleVal should equal -10. In this case, previousVal (the accumulator) is already set to 0 and we subtract each item from it in turn (0-1-2-3-4 = -10).

Definitely check out the MDN docs on Reduce for more examples.


thank you so much! you helped me understand a part that went completely over my head. I actually had all the code there but had to change the - into a +. so annoying.

1 Like

@DaveC That answer helped out huge. I couldn’t understand why I was getting errors until I compared your code side by side with my code. I had an extra closing brace that I wasn’t seeing/comprehending until the comparison.