# Sum All Odd Fibonacci Numbers

Code is not working.
I think i created an array with Fibonacci numbers, i extract the Odd nembers;
but i can’t to Sum it.
Can anybody help me?

``````function sumFibs(num) {

if (num === 1) {
return num;
}

let fibArr = [0, 1];
let fibArrOdd = [];  //array with Odd numbers

// create a Fibonacci array:
for (let i = 1; i < num; i++) {
fibArr.push(fibArr[i]+fibArr[i-1]);
}
console.log(fibArr); //test

// create a Fibonacci Odd numbers Array:
for (let i = 0; i < fibArr.length; i++) {
if (fibArr[i]%2 !== 0) {
fibArrOdd.push(fibArr[i]);
}
}
console.log(fibArrOdd); //test
console.log(fibArrOdd[2]); //test

// Here is the problem (maybe not only here?). I try to sum all Odd numbers, and I have "undefined" in a console:
for (let i = 0; i < fibArrOdd.length; i++) {
let fibArrOddSum;
fibArrOddSum = fibArrOddSum + fibArrOdd[i];
}
}

console.log(sumFibs(4))
``````

You are declaring the `fibArrOddSum` variable inside of the loop, which means it resets on each loop iteration.

Here is some conventional formatting for your code:

``````function sumFibs(num) {
if (num === 1) {
return num;
}

let fibArr = [0, 1];
let fibArrOdd = [];  //array with Odd numbers

// create a Fibonacci array:
for (let i = 1; i < num; i++) {
fibArr.push(fibArr[i] + fibArr[i-1]);
}
console.log(fibArr); //test

// create a Fibonacci Odd numbers Array:
for (let i = 0; i < fibArr.length; i++) {
if (fibArr[i]%2 !== 0) {
fibArrOdd.push(fibArr[i]);
}
}
console.log(fibArrOdd); //test
console.log(fibArrOdd[2]); //test

// Here is the problem (maybe not only here?). I try to sum all Odd numbers, and I have "undefined" in a console:
for (let i = 0; i < fibArrOdd.length; i++) {
let fibArrOddSum;
fibArrOddSum = fibArrOddSum + fibArrOdd[i];
}
}
``````

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