Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Can anybody find the issue with the code below?

Your code so far

function sumFibs(num) {
  //generate the sequence
let seq =[0,1]


for(let i = 2; i < num; i++){
    seq.push(seq[i-1] + seq[i-2])
}

  return seq.filter(elem => elem % 2 != 0).reduce((i,elem)=> i + elem,[]);
}

console.log(sumFibs(1));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

Challenge Information:

Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Welcome to the forum @rohithoro96

Here are the console logs of your code:
fib: [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
seq: 11351321

The return statement is joining the odd Fibonacci numbers together.

Happy coding

Hello there!
Thank you checking into my code.
I wonder why is the code behaving that way rather than adding the odd numbers.

1 Like

because your starting value for the reduce is an empty array, and [] + 1 gives "1" as in a string, and if that is a string, it concatenates all the others later

Well, I tried debugging by replacing the starting value with 0 as well still didn’t work.
This might not be the right approach I guess.
All I was trying to do is -

  1. Generate the fib. Sequence and push them inside an array.
  2. Filter all the odd numbers from the array.
  3. Calculate and return the sum of odd numbers

the reduce having a 0 as starting value is much better than having an empty array. What is going on now? Is the output still a concatenation of numbers?

Yes, it is still concatenation of numbers.

show your code please

Sure , Here you go…

function sumFibs(num) {
  //generate the sequence
let seq =[0,1]


for(let i = 2; i < num; i++){
    seq.push(seq[i-1] + seq[i-2])
}

  return seq.filter(elem => elem % 2 != 0).reduce((i,elem)=> i + elem,0);
}

console.log(sumFibs(1));```

it is not concatenating the numbers, I am executing your code and it returns numbers correctly

the issue is an other

Given a positive integer num , return the sum of all odd Fibonacci numbers that are less than or equal to num .

are you getting these numbers? or are you getting the first num Fibonacci numbers?

Please refer to the snap below…

Double check the bounds. How big are the numbers supposed to get?

Pardon me , I didn’t get you .What bounds?? Can you please elaborate?

This say to create num Fibonacci numbers. That’s not what the instructions as for though.

Finally working …Thanks for the input

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.