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
Finding upper elements in array 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.
Therefore, let's write the code for this function ?
Using for Loop
The most straightforward approach uses a for loop to iterate through the array and check each element:
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
[ 56, 76, 45, 56 ]
Using filter() Method (Recommended)
A more concise approach uses the built-in filter() method:
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreater = (arr, num) => {
return arr.filter(element => element >= num);
};
console.log(findGreater(arr, threshold));
[ 56, 76, 45, 56 ]
Using reduce() Method
Another functional approach uses reduce() to build the result array:
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreater = (arr, num) => {
return arr.reduce((result, element) => {
if (element >= num) {
result.push(element);
}
return result;
}, []);
};
console.log(findGreater(arr, threshold));
[ 56, 76, 45, 56 ]
Comparison
| Method | Readability | Performance | Functional Style |
|---|---|---|---|
| for loop | Good | Fastest | No |
| filter() | Excellent | Good | Yes |
| reduce() | Good | Good | Yes |
Conclusion
The filter() method is recommended for its readability and functional programming style. Use the for loop approach when performance is critical for large arrays.
