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:
trueAt 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:
trueNone 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:
trueCommon 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
falseFunctions used in this recipe
- Array.prototype.every — Checks that every element of an array passes a test.
- Array.prototype.some — Checks whether at least one element passes a test.