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
Getting equal or greater than number from the list of numbers in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should return an array of all the elements from the input array that are greater than or equal to the number taken as the second argument.
Example
Following is the code ?
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreater = (arr, num) => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] < num){
continue;
};
res.push(arr[i]);
};
return res;
};
console.log(findGreater(arr, threshold));
Output
This will produce the following output in console ?
[ 56, 76, 45, 56 ]
Using filter() Method
A more concise approach uses the filter() method to achieve the same result:
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreaterWithFilter = (arr, num) => {
return arr.filter(element => element >= num);
};
console.log(findGreaterWithFilter(arr, threshold));
[ 56, 76, 45, 56 ]
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| for loop | Longer | More verbose | Slightly faster |
| filter() | Shorter | More readable | Slightly slower |
Handling Edge Cases
Here's a more robust version that handles edge cases like empty arrays and invalid inputs:
const findGreaterSafe = (arr, num) => {
if (!Array.isArray(arr) || typeof num !== 'number') {
return [];
}
return arr.filter(element => typeof element === 'number' && element >= num);
};
// Test with edge cases
console.log(findGreaterSafe([], 10)); // Empty array
console.log(findGreaterSafe([1, 2, 'a', 4], 2)); // Mixed types
console.log(findGreaterSafe([5, 10, 15], 8)); // Normal case
[] [ 4 ] [ 10, 15 ]
Conclusion
Both the for loop and filter() methods effectively find elements greater than or equal to a threshold. The filter() method offers cleaner, more readable code, while the for loop provides slightly better performance for large arrays.
