Sum All Odd Fibonacci Nums

Sum All Odd Fibonacci Nums
0.0 0

#1

Tell us what’s happening:
I am stuck. I can’t figure out how to combine these functions. And I tried using .filter(oddNums) in my final return statement and it didn’t work also. Thanks in advance any help is much appreciated!

Your code so far



//array with all fibonnacci numbers
function fibs(num) {
  var x=[1,1];
  while (((x[x.length-1]) + (x[x.length-2]))<=num){
   x.push((x[x.length-1]) + (x[x.length-2]));
    
  }
 return x;
  
  //filter only odd numbers using %2 !=0
  function oddNums(x){
    var oddArr= [];
    for (var i=0; i<=x.length; i++){
    if (x[i] %2 !=0){
     oddArr.push(x[i]);
    }}
  return oddArr;
    
  //sum all odd numbers using reduce function
 function sum(acc, val){
   return acc+val;}
 
    //final return
 return oddArr.reduce(sum());
}}
sumFibs(10);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7.

Link to the challenge:


#2

Problem:

function fibs(num) { ... } Function declared.

sumFibs(10); Different function called.

And check the return statement on line 7. This stops code execution.


#3

Thanks for your reply! ok I fixed that name error but do I just delete the return statement on line 7? i did that but it didn’t help. the console.log(x) works still. but I dont know how to connect these functions together.


#4

You’re having an issue with scopes and your returns here. Once that is fixed and if you choose to split them into seperate functions you can do something like this judging by what you’ve done so far: oddNums(fibs(num)).reduce(sum); your approach to the problem is good, it just seems like the code doesn’t quite match what you think it should do. Let me know if you need more help.

To help you get started I ran it through a beautifier and added some comments.

//array with all fibonnacci numbers
function fibs(num) { //Only function visible outside the scope of this function.
  var x = [1, 1];
  while (((x[x.length - 1]) + (x[x.length - 2])) <= num) {
    x.push((x[x.length - 1]) + (x[x.length - 2]));

  }
  return x; //fibs will return here and all the code below is unreachable as it's scoped inside fibs

  //filter only odd numbers using %2 !=0
  function oddNums(x) {
    var oddArr = [];
    for (var i = 0; i <= x.length; i++) {
      if (x[i] % 2 != 0) {
        oddArr.push(x[i]);
      }
    }
    return oddArr;

    //sum all odd numbers using reduce function
    function sum(acc, val) {
      return acc + val;
    }

    //final return
    return oddArr.reduce(sum());
  }
}

#5

Thanks so much for the help! Got if figured out finally!