How to check if at least one element of an array is true in D
Overview
We use the any() method to check if at least a single element in an array is true.
Syntax
any(array)
Parameters
array: The array we want to check.
Return value
A boolean value is returned. If at least one element is true, then true is returned. Otherwise, false is returned.
Example
// import std.stdioimport std.stdio;import std.algorithm;// main methodvoid main(string[] args) {// create arrayint[] array1 = [50, 20, 10, 45, 34];int[] array2 = [0, 0, 0, 0];int[] array3 = [false, false, true];string[] array4 = [];// check if elements are truewriteln(any(array1)); // truewriteln(any(array2)); // falsewriteln(any(array3)); // truewriteln(any(array4)); // false}
Explanation
- Lines 8–11: We create four arrays.
- Lines 14–17: The arrays we create are checked to see if at least one element evaluates to true using the
any()method. Then, we print the values.