# Tally the Banana explainer

Aim of the puzzle: Use the `.reduce()` array method to count the number of bananas in an array of fruits.
Walk through of solution:
`.reduce()` is used to calculate a single value from an array, for example, adding all the numbers of an array into a single sum.

`.reduce()` uses 2 arguments: a callback function, and a starting value. The callback also uses 2 parameters: the total value so far, and the current value.

For example, in the following code:

``````[1, 2, 3].reduce((total, currentNumber) => {
}, 0)
// This returns 6
``````

In this code, `.reduce()` has a callback function and `0` as a starting value for the callback. The callback function iterates over the array, and adds each element to the total value.

In this puzzle, we want `.reduce()` to only add to `total` if `currentFruit === 'banana')`. If this is true, `total` will be incremented by `1`, and then `total` is returned. If the `currentFruit` is not `'banana'`, `total` is returned without being incremented, and `.reduce()` moves on to the next element.

To complete the puzzle, add the test `currentFruit === 'banana'` to the if statement, then add `total++` to the code block. After the if statement, add `return total`.

Sample code solution:

``````import { fruits } from 'grasshopper.belafonte';
for (let fruit of fruits) {
console.log(fruit);
}
let bananaCount = fruits.reduce((total, currentFruit) => {
if (currentFruit === 'banana') {
total++;
}
}, 0);

console.log(bananaCount);
``````

Javascript Concepts: `.reduce()`, Arrays, Array Methods, If Statements, Import Declarations, Return Statements, For Of Loops, `console.log()`
Additional Code (hidden code that runs before the puzzle’s code):

``````const _fruits = [...Array(7)].map(() => pickRandom(['banana', 'banana', 'kiwi', 'mango', 'guava', 'orange', 'apple', 'banana']));

defineModule(
'grasshopper.belafonte',
{
fruits: _fruits
}
);

``````
2 Likes

Hello! Shouldn’t be a semicolon before the return?

[1, 2, 3].reduce((total, currentNumber) => {