Check if all values in an array are true then return a true in JavaScript
In this short article, we will show you how to check if all values in an array are true then return a true boolean statement in JavaScript.
Checkout more articles on JavaScript
Let’s assume that we have the following array of booleans.
1 2 | var arr1 = [true, false, true]; var arr2 = [true, true, true]; |
In the above code, the value of arr1
should be false
as one item in the list is false
while the value of arr2
should be true
because all items are true
.
We can use the every() method to get the desired output.
1 2 3 4 5 6 7 8 9 10 11 | var arr1 = [true, false, true]; var arr2 = [true, true, true]; let myFunction = arr => arr.every(v => v === true); myFunction(arr) { return arr.every(v => v === true); } console.log(myFunction(arr1)); // Output: false console.log(myFunction(arr2)); // Output: true |
We can simply pass the Boolean
as a callback to every()
method.
1 2 3 | myFunction(arr) { return arr.every(Boolean); } |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂