Imagine you have a chest full of coins. You could count them ONE BY ONE... or use .reduce() to add them all up at once!
.reduce() takes every item in an array and squishes them together into ONE value. It's perfect for:
How it works:
• sum starts at 0 (the second argument)
• For each item, add it to sum
• After all items, sum is your final answer!
Remember: In Neon Patrol, you used .findIndex() to FIND items. Now with .reduce(), you can COMBINE all items into one value!
Change the treasures array to have different values. What happens when you add more items?
The second argument is the STARTING value. What if you start from 100 instead of 0?
reduce() can do ANY operation! Change + to * to multiply instead of add.
Can reduce() find the maximum? Use Math.max() inside!
Combine filter() and reduce()! First filter treasures over 30, then sum them!
.reduce() squishes an entire array into ONE value0).filter() and .map() for superpowers!