Sum All Odd Fibonacci Numbers -HELP!

Why is it summing 10 digits instead of summing til num 10. I am getting 99 instead of 10 !
Here is my code:

``````function sumFibs(num) {
var fib=[1,1];
for(var i=2; i<num; i++){
var nextNumber=fib[i-1]+fib[i-2]
var fibi=fib.push(nextNumber)
}
return fib.filter(function(a){
return (a %2 !=0);
})
.reduce(function(a,b){
return a+b;
})
return fib;
}
console.log(sumFibs(10));  // 99
``````
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (`</>`) will also add backticks around text.

Note: Backticks are not single quotes.

I´ll do, thank you. ‘’’ ‘’’

Before the function’s return statement, `fib` looks like:

``````[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]
``````

Then, after you filter it, you are left with an array which looks like:

``````[ 1, 1, 3, 5, 13, 21, 55 ]
``````

which then you reduce to `99`.

The `reduce` method will still iterate over the 7 elements present in the array filter returns, so you are just summing those 7 numbers.

You can modify your `filter` to only include values less than 10 while also checking for the odd numbers. This way, your `reduce` will only iterate and sum the following numbers:

``````[ 1, 1, 3, 5 ] // sum is 10
``````
1 Like

Thank you for your answer. Sorry i am very new( 2 months) to coding and maybe too old to start
;(
I know where from 99 is coming, just can’ t do it correctly…
thought ‘’’(i < num)’’’ is doing it, but was wrong.

1 Like

Why would you use `i < num` inside the filter’s callback function? There is no variable named `i` in it. There is another variable you could use though.

1 Like