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.stdio
import std.stdio;
import std.algorithm;
// main method
void main(string[] args) {
// create array
int[] array1 = [50, 20, 10, 45, 34];
int[] array2 = [0, 0, 0, 0];
int[] array3 = [false, false, true];
string[] array4 = [];
// check if elements are true
writeln(any(array1)); // true
writeln(any(array2)); // false
writeln(any(array3)); // true
writeln(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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources