Check if all values in an array are true then return a true in JavaScript
📅December 27, 2021
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
- Detect a mobile device using JavaScript
- Download a file using JavaScript
- Get the YouTube video ID from a URL using JavaScript
- Get all query string values using JavaScript
Let’s assume that we have the following array of booleans.
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.
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.
myFunction(arr) {
return arr.every(Boolean);
}
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂