Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if all array elements match a condition

Short answer

every() returns true if the function returns true for each element:

const ages = [21, 34, 19, 45];
 
console.log(ages.every((age) => age >= 18));

Output:

true

At least one

some() is enough if one matching element is sufficient:

const ages = [21, 34, 15, 45];
 
console.log(ages.some((age) => age < 18));

Output:

true

None of the elements

There is no separate method for none. Negate some():

const files = ['a.txt', 'b.txt'];
 
console.log(!files.some((name) => name.endsWith('.exe')));

Output:

true

Common mistake

For an empty array every() always returns true. If that is wrong for your task, check the length too:

const tasks = [];
 
console.log(tasks.every((task) => task.done));
console.log(tasks.length > 0 && tasks.every((task) => task.done));

Output:

true
false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.