Using reduce for Finders keepers

Tell us what’s happening:
I keep getting the error undefined when attempting this challenge. I know I can use a loop for this but I want to use reduce. Please have a look at my code~

Your code so far


function findElement(arr, func) {
  arr.reduce(function(final, num){
    return num % 2 === 0;  
  }, 0)
}

findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })

Your browser information:

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

Link to the challenge:

the function findElement doesn’t have a return statement, so it returns undefined by default

you are not using the func function parameter

plus - are you sure you know what reduce does? are you sure it is the best method here?

1 Like

Hi ieahleen, thanks for your reply.

I have some difficulty using reduce, which is why I forced myself to use it for this exercise.

My reasoning was this: I wanted to iterate over each number in the array and have it checked against the reduce function condition, and finally have left the only number that fulfills this.

So I’ve modified the code as per your suggestions and I’m still getting undefined.

function findElement(arr, func) {
  return arr.reduce(function(final, num){
    func;  
  }, 0)
}

findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })

Thanks for your help! (also I just realised that reduce will return all the numbers that fulfill the condition, is that possibly why I get undefined as an error?)

reduce needs a callback with two parameters: an accumulator and a current value, the current value will be the current value on the array, and the accumulator the value returned from previous iteration
the documentation I linked before expand on this

You can solve it with reduce, but it is unnecessary complicated, above all if you are already not familiar with the easier way to use the method (like summing all the numbers in an array, or using it to concatenate strings in an array)

right now you are getting undefined because the reduce method is returning undefined as its callback doesn’t have a return statement

you are also still not using func. func is a function, which you should use to test the elements in the array, you are just writing it there, not calling the function and above all not passing anything to the function

I highly suggest you try solving this challenge first without using methods, then you can complete it a second time

Alright I’ll try a simpler solution first. Clearly reduce is only increasing my problems, heh