Sum All Odd Fibonacci Numbers (almost there)

Tell us what’s happening:
So, I’m almost there, I think, but when the 75024 argument is run through the function it goes one number in the sequence beyond what it is supposed to. Any ideas why it is doing that? Any help would be appreciated.

Your code so far

function sumFibs(num) {
  var notSum = 2;
  var notArr = [1,1];
  var arr = [1,1];
  var junk;
    
   while (notSum <= num){
      var last = notArr.length-1;
      var last2 = notArr.length-2;
      junk = notArr[last] + notArr[last2];
      notArr.push(junk);
    if (junk % 2 != 0 ){ 
      notSum = notSum + junk;
      console.log( notSum);
      arr.push(junk);
    }
   }
  
  return arr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0) ;
}

sumFibs(75024);

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/sum-all-odd-fibonacci-numbers

That’s because, with your current code, the second last junk generated is 46368, so the if block is never triggered and notSum would still be 28657 at that point. Since 28657 is less than 75024, the while block will therefore run another time and assign 75025 to junk.

I personally think that the logic involving notSum is convoluted and redundant. I think you can remove that logic and make use of reduce().

I hope that helps!

1 Like

So, this is what I came up with based on what you said. What do you think?

function sumFibs(num) {
  var notSum = 1;
  var notArr = [0,1];
  var last;
  var last2;
   while (notSum < num){
      last = notArr.length-1;
      last2 = notArr.length-2;
      notSum= notArr[last] + notArr[last2];
      if (notSum <= num){
        notArr.push(notSum);
      }
   }
  notArr.forEach(function (value, index){
    if (value % 2 == 0){
     notArr.splice(index, 1);
    }
  });
  
  return notArr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0) ;
}

sumFibs(75024);

I think that’s good. :smile: You should wrap your code with the [spoiler][/spoiler] tags in case others looking for help see it!

In case you are interested in doing things differently, here are a few things that you may find useful in the future:

Instead of using splice() inside forEach(), you can achieve the same with filter(). So instead of:

  notArr.forEach(function (value, index){
    if (value % 2 == 0){
     notArr.splice(index, 1);
    }
  });

You could write:

notArr = notArr.filter(function(value) {
  return value % 2 !== 0;
});

In this particular case, you may find that the solution is still very easy to follow if you just do the “filtering” inside reduce() like this:

return notArr.reduce(function(acc, val) {
  if (val % 2 !== 0) {
    acc += val;
  }

  return acc;
});

Good job on getting it one. :smile: Good luck!