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
Filtering array within a limit JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and an upper limit and lower limit number as second and third argument respectively. Our function should filter the array and return a new array that contains elements between the range specified by the upper and lower limit (including the limits).
Syntax
const filterByLimits = (arr, upper, lower) => {
return arr.filter(element => element >= lower && element <= upper);
};
Parameters
- arr - The array of numbers to filter
- upper - The maximum value (inclusive)
- lower - The minimum value (inclusive)
Example
const array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
const lower = 18;
const upper = 20;
const filterByLimits = (arr = [], upper, lower) => {
let res = [];
res = arr.filter(el => {
return el >= lower && el <= upper;
});
return res;
};
console.log(filterByLimits(array, upper, lower));
Output
[ 18, 20, 18, 19, 18, 20 ]
Simplified Approach
We can make the function more concise by removing unnecessary variables:
const filterByLimits = (arr, upper, lower) => {
return arr.filter(element => element >= lower && element <= upper);
};
const numbers = [5, 12, 8, 3, 15, 7, 20, 1];
console.log(filterByLimits(numbers, 10, 5));
[ 5, 8, 7 ]
How It Works
The function uses the filter() method to create a new array containing only elements that satisfy the condition element >= lower && element . The logical AND operator ensures both conditions must be true for an element to be included.
Conclusion
Filtering arrays within limits is efficiently handled using the filter() method with range conditions. This approach creates a new array without modifying the original data.
