Is possible to use .reduce until a condition is met?

freeCodeCamp Challenge Guide: Sum All Odd Fibonacci Numbers

I tried doing the exercise with .reduce to get the sum until it was <= num but it didn’t work. I have noticed in the different answers that they first get the array with the odd numbers that meet the condition and then add it.
What I was trying to do is apply .reduce to an array with odd numbers <= num (perhaps it was not the focus of the exercise) but it raised me the doubt that if .reduce can be stopped when meeting a condition.
Thank you, sorry for my English and I am a beginner. :smile:

Hi @psanchezp31 !

It would help to see your code.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you. This was an attempt:

function sumFibs(num) {
var i = 1;
var odds =[1];

while(i<=num){
  if(i%2==1){
    odds.push(i)
  }
  i++
}
const fibonacci = odds.reduce(function(accumulator, currentValue) {
  var sum = accumulator + currentValue
  if(sum <= num){
    return sum
  }  
})
  return fibonacci
}

sumFibs(10);

I can see two ways to use reduce. One way would be what you have here - filtering out the evens. Of course, you could also use a filter method for that. The other option would be to just use reduce and if the current is odd, return the sum of the accumulator and current - if the current is even, just return the accumulator - that would keep the even numbers out of the sum because only odds are added to the accumulator.

1 Like

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