-
Notifications
You must be signed in to change notification settings - Fork 11
JavaScript Array Functions
These help you test if something is true for every element or some elements of an array.
We need some data to test, consider an array of numbers;
const nums = [34, 2, 48, 91, 12, 32];
Now let's say we want to test if every number in the array is less than 100
.
nums.every(n => n < 100)
;
// true => all numbers in the array are less than 100
-
every
loops over the array elements left to right - For each iteration, it calls the given function with the current array element as its 1st argument.
- The loop continues until the function returns a falsy value and in that case
every
returnsfalse
- otherwise it returnstrue
some
also works very similar to every
-
some
loops over the array elements left to right. -
For each iteration, it calls the given function with the current array element as its 1st argument.
-
The loop continues, until the function returns a truthy value and in that case
some
returnstrue
- otherwise it returnsfalse
Now let's use some
to test if some number in the array is odd,
nums.some(n => n % 2 == 1);
// true => 91 is odd