Tell us what’s happening:
Trying to use .reduce with conditional statements.
I’m trying to use .reduce instead of a combination of .filter and .reduce. Am I allowed to use an if statement inside the callback for the reduce method? How can I correct this code?
**Your code so far**
function sumFibs(num) {
const fibArr = [1, 1];
let nextNum = undefined;
while ((nextNum = fibArr[0] + fibArr[1]) <= num) {
fibArr.unshift(nextNum)
}
// Works.
return fibArr.filter(x => x % 2 != 0)
.reduce((a, b) => a + b);
// Does not work.
return fibArr.reduce((acc, curr) => {
if (curr % 2 != 0) acc += curr;
return acc;
});
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36
I think you cannot use a return in an arrow-function, so that’s why it also complaints about the if.
However you can use a ternary-operator and if you do it right, it works.
If you don’t initialise it with 0, it’ll by default take the first item in the array, which (in some cases) is an even number, and therefore shouldn’t be included in the sum.