Wrong Hint: Sum All Odd Fibonacci Numbers

Tell us what’s happening:

This is the intermediate solution offered for this challenge; however it’s not working for all values. I think it’s because it’s checking the sum for all numbers and not only odd numbers.

Your code so far

function sumFibs(num) {
    // Perform checks for the validity of the input
    if (num < 0) return -1;
    if (num === 0 || num === 1) return 1;

    // Create an array of fib numbers till num
    const arrFib = [1, 1];
    let nextFib = 0;
    // We put the new Fibonacci numbers to the front so we
    // don't need to calculate the length of the array on each
    // iteration
    while((nextFib = arrFib[0] + arrFib[1]) <= num) {

    // Sum only the odd numbers and return the value
    return arrFib.reduce((acc, curr) => {
        return acc + curr * (curr % 2);

// test here

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0.

Link to the challenge:


I’ll admit that this one took me several minutes to find the problem. The problem is in your reduce method:

    return arrFib.reduce((acc, curr) => {
        return acc + curr * (curr % 2);

The reduce method starts on the first iteration by putting the first value into acc and the second value into curr. So, the first value never gets checked if it is odd. So, if the last fib number is even, it gets added in accidentally.

There are a couple ways to fix it. I might have gone with a push use unshift - I tend to prefer it because I think in most implementations it is faster. Of course you’ve have to adjust arrFib[0] + arrFib[1] to be arrFib[arrFib.length -1] + arrFib[arrFib.length -2]. Then when you do your reduce, it will always start with 1 so you will be fine.

Another option (if you must use unshift) would be to use reduceRight, so it will start the summing from the other side of the array.

There are of course other solutions, but these solutions keep the basic structure of this code. Personally I find this solution a little inefficient (I don’t think you need that big array), but it is a viable solution and is fairly intuitive.

1 Like

instead of using reduce() directly, you could filter out even numbers using filter(), so you just sum together the odd numbers - it requires more resurces but the result will be consistent

Sorry but that is not my method, I just wanted to notice people responsible for the Hints that this particular hint was wrong so they can be able to change it. I guess it’s not the right place to do this?

I would guess that making an issue on the git repo would be the way to go.