Hello! How can I do that reduceToAllTrue returns true when all values are truthy.
Here it is my code. Can you explain to me why doesn’t work? How should I do instead? I got undefined.
What I thought : I make loop inside the sourcearr and for every element see if it truthy by Boolean(el) then add to the accumulator (which has a true value as initial value) , else turn the element into truthy value by Boolean(el)*0; ( I notice now that false*false is still false… so this part definitely wrong). I know the output should be like ‘5razmatazz’ expected to be true, if this arr is given sourceArray = [1, 2, true, "razmatazz"]
I have to check in the source arr and if every element in it is true, then reduceToAllTrue(sourceArray) should be true. I don’t know, maybe I haven’t understood the instruction even. I thought I should check every value and if they are true should add to the accumulator and if not should turn it in true and add it.
I supposed to create a function that like the one I did in the 3rd photo (which pass the test) however, I want to do the same only using reduce (I commented out that part). The second photo is the test for this exercise.
Right, that is what I thought it was. I’m sure there are a few ways of doing it. I didn’t really think much about it but here is one version.
Not really sure how understandable this pseudo code is.
if accumulator is truthy
if currentValue is truthy
set accumulator to Boolean(currentValue)
else set accumulator to false
return accumulator
return accumulator
There might be a better way, like I said I didn’t really think much about it.
function reduceToAllTrue(sourceArray){
const result = sourceArray.reduce((acc, value) => {
// If the `acc` is false, it means the previous
// value was falsy, so we always return false now
if (acc === false) {
return acc;
}
return Boolean(value);
}, true)
return result
}
reduceToAllTrue([1,"w",true, false]);