HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Truth check all values in a JavaScript array

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptcheckalltrutharrayvalues

Problem

As mentioned in a previous article, JavaScript uses type coercion in Boolean contexts, such as conditionals. This means that values are considered either truthy or falsy depending on how they are evaluated in a Boolean context. Combining this with the Boolean function and truth checking a collection of values becomes a breeze.
Using Array.prototype.every(), we can easily check if all values in an array are truthy. The Boolean function can be used as a default callback to check if all values are truthy, but specifying a custom callback function is also possible.
Using Array.prototype.some(), we can check if any values in an array are truthy. The Boolean function can be used as a default callback to check if any values are truthy, but specifying a custom callback function is also possible.
Similarly, Array.prototype.some() can be used to check if any values in an array are falsy. Again, the Boolean function can be used as the default callback, but you can also specify a custom callback function.
Taking this one step further, Array.prototype.every() can be used to check if all objects in an array have a given property. This is useful for validating data, for example. Simply checking for the existence of a property will return a truthy or falsy value depending on whether the property exists or not.

Solution

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true


Using Array.prototype.some(), we can check if any values in an array are truthy. The Boolean function can be used as a default callback to check if any values are truthy, but specifying a custom callback function is also possible.
Similarly, Array.prototype.some() can be used to check if any values in an array are falsy. Again, the Boolean function can be used as the default callback, but you can also specify a custom callback function.
Taking this one step further, Array.prototype.every() can be used to check if all objects in an array have a given property. This is useful for validating data, for example. Simply checking for the existence of a property will return a truthy or falsy value depending on whether the property exists or not.

Code Snippets

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
const any = (arr, fn = Boolean) => arr.some(fn);

any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true
const none = (arr, fn = Boolean) => !arr.some(fn);

none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true

Context

From 30-seconds-of-code: check-array-values-are-truthy

Revisions (0)

No revisions yet.