Reputation: 53
I was trying to solve the following question:
Write a function that returns true if all array elements are true. Use reduce
The is the solution I made up
function allTrue(values) {
if ( values[0] === false) return false
if (values.length === 0) return true
let result = values.reduce( (final, value) => final = value === true, true)
return result ? true : false
}
My question is, whether it is possible to move the external conditions into the reduce method's body or not.
In other words, if I was required to use a single reduce method to solve it, can I implement it?
I tried manipulating the final in the reduce, but it is modified later in next iterations
For instance the following test should return false but returns true
allTrue([false, true])
Any explanation would be appreciated, thank you
Upvotes: 2
Views: 77
Reputation: 4184
We can use every
as well to find the solution to this. Below is the snippet for both every
as well as reduce
var allTrue_Every = (arr) => arr.every(d => d == true)
console.log(allTrue_Every([true, true]))
console.log(allTrue_Every([true, false]))
var allTrue_Reduce = (arr) => arr.reduce((r, d) => r && d, true)
console.log(allTrue_Reduce([true, true]))
console.log(allTrue_Reduce([true, false]))
Upvotes: 0
Reputation: 147206
The reason your code doesn't work is that the reduce
only returns the result of the comparison of the last element in the array with true
. Since the last element in [false, true]
is true
, it returns true
.
Note that your code is overly complex, you have already effectively included your conditions in the reduce
(giving an initial value of true
means that a zero-length array will return true
). Your one issue is that the code in the reduce
is incorrect, you should be checking whether all the previous values are true
as well as the current one by and'ing the current value with the and of all the previous values:
const allTrue = (values) => values.reduce((curr, value) => curr && value, true);
console.log(allTrue([]));
console.log(allTrue([true]));
console.log(allTrue([false]));
console.log(allTrue([true, true, true]));
console.log(allTrue([false, true]));
Upvotes: 4
Reputation: 84
I think this can be help:
function allTrue(values) {
return values.reduce((final, value) => final && value)
}
Upvotes: 1