I put the console.log()s to see where the problem occurs and the first part seems correct, however, reduce is still undefined when I remove the console.log()s. I am probably making a mistake with the way I design .reduce().
But yea, your reduce can’t work like that. You’re probably getting some sort of an error about .push(). You can’t push onto a number, but when you don’t provide an initial value for .reduce(), the first element of the array is used.
But I agree, that reduce isn’t the right method here. reduce is for taking an array down to a value. What you want is a method that takes one array and makes a new array where each element in the new array is made from the corresponding element in the old array.
How do I provide an initial value in the case of an array? Does the method introduced in the challenge that explains reduce would work? It was like this:
You could do this with reduce, but it would have to be a different method than what you are doing. Personally, I prefer the approach you are doing - it will be more readable.
Yeah, I will change it to map()
Ding ding ding!
I was just curious if there is a way to make reduce work here
Yes you could. In fact, you could use only that. You accumulator would be the array you want.
And yes, with your 2 method approach (which again, I think is better because it is more readable, you could replace either of those methods with reduce - it’s just not a good idea - again, readability.
But that might be a good exercise - write your own mapping, filtering, and finding methods (or just as functions) using only reduce. reduce is a hard method for new people to understand. But that would help.