Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Could use some help making this code work. I can’t understand why it doesn’t but feel like I made the same mistakes as last time.

Your code so far

function sumFibs(num) {
  let arr=[]
  for(let i=1;i<=num;i+=i)
  arr.push(i)
  for(let j=2;j<=arr.length;j+=2)
  arr.splice(j);
  (arr) => {
    return arr.reduce((total, current) => {
        return total + current;
    }, 0);
    
}
  return arr

}
sumFibs(4)

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Link to the challenge:

Lets start with some formatting so we can understand the code:

function sumFibs(num) {
  let arr = [];
  for (let i = 1; i <= num; i += i) {
    arr.push(i);
  }
  for (let j = 2; j <= arr.length; j += 2) {
    arr.splice(j);
  }
  (arr) => {
    return arr.reduce((total, current) => {
      return total + current;
    }, 0);
  }
  return arr;
}
sumFibs(4)

Can you explain what this code is supposed to do? Not what the literal syntax means, but why?

Side note - if you aren’t sure exactly how to use fancy syntax, you can stick to only for loops, while loops, and if statements. That will solve 99% of the challenges without any splice or reduce.

The first for loop is meant to loop in the Fibonacci sequence of all integers before and including ‘num’, by adding i to its self. I then put them into an array. The second for loop is meant to loop through all the even numbers before and including num, so that then I could remove them from the array by using splice. Then the reduce function is meant to find the sum of all the numbers in the array, and return it.

So a few issues

  1. The first loop isn’t generating any Fibonacci numbers. It’s making every single integer.

  2. Splice still creates confusing results so it shouldn’t be used in a loop. Also, you aren’t splicing out every other number. Also, it isn’t the case that every other Fibonacci number is even.

  3. I don’t think your reduce is running.

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