Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking if all array values are smaller than a limit using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers and a number. We should return true if all the numbers in the array are smaller than the number given as second argument, false otherwise.
Using Array.every() Method
The Array.every() method tests whether all elements in the array pass the test implemented by the provided function. It returns true if all elements satisfy the condition, false otherwise.
Example 1: All Values Smaller
Following is the code −
const arr = [5, 34, 23, 14, 78, 45, 78];
const limit = 99;
const checkEvery = (arr = [], limit = 1) => {
const allSmaller = arr.every(el => {
return el < limit;
});
return allSmaller;
};
console.log(checkEvery(arr, limit));
true
Example 2: Some Values Larger
Let's test with a scenario where some values exceed the limit:
const arr2 = [5, 34, 23, 14, 105, 45, 78]; const limit2 = 99; console.log(checkEvery(arr2, limit2));
false
Simplified Version
We can simplify the function by directly returning the result of every():
const checkEverySimple = (arr = [], limit = 1) => {
return arr.every(el => el < limit);
};
// Testing with different arrays
console.log(checkEverySimple([10, 20, 30], 40)); // true
console.log(checkEverySimple([10, 20, 50], 40)); // false
console.log(checkEverySimple([], 10)); // true (empty array)
true false true
Key Points
-
Array.every()returnstruefor empty arrays (vacuous truth) - The method stops checking as soon as it finds the first element that doesn't satisfy the condition
- All elements must satisfy the condition for the method to return
true
Conclusion
Array.every() provides an elegant solution for checking if all array elements meet a specific condition. It's efficient because it short-circuits on the first failing element.
