Hello ,
back at it again…
After multiple tries and a lot of frustration I managed to figure out this code.
function oddProduct(arr) {
return arr.filter( x => (x % 2 == true) ).reduce( (a,b) => a*b ,1 );
}
This is supposed to multiply all the odd integers in an array and return that value.
So my question is…
When I used arr.filter, I tried using (x => (x % 2 == 0)) first, but realized that would give me EVEN numbers, so then I tried “true” and “voila” it worked… So can someone help me understand why having (x % 2 == true) ) works and returns the odd numbers?
Is it because true integers are 1,2,3,4, etc… which means there IS a remainder meaning it is an odd number?
Also when I use the reduce function , reduce( (a,b) => a*b ,1 ) how would the variables (a,b) know which numbers to multiply?
I would suggest you use === instead of ==. In this instance it would force you to think more about what the % operator returns and what you are actually looking for from that return value. With == you are depending on the JS interpreter to do some conversions behind the scenes, which I guess is fine if you really understand what that implies, but often it can cause bugs on edge cases.
As @ILM said, JS is weird. Using strict equality will take all of that weirdness out of the equation.
Yeah, as @ILM stated that does seem to help me understand it a bit more. On another note, do you happen to know how the reduce function works?
For example when I use the reduce function , reduce( (a,b) => a*b ,1 ) how would the variables (a,b) know which numbers to multiply ? Does it work like the filter function and assign new variables to the array element? And does it execute the function until there are no more elements?
the reduce method call the function you pass in as argument with different values each time. The first parameter a is the accumulator, the second is the current value
yoo could write it as (product, number => product * number to havemore descriptive names for tbe function parameters
Ah okay , I was confused since I thought the accumulator added the elements together but now I realize you can call accumulator * currentValue … Okay thanks, will look for some videos so that I can understand it fully.