How to use Array Reduce Method In Javascript
It uses the reduce method to accumulate elements less than X into a new array, providing a concise way to apply filtering logic while reducing the array.
Example: Implementation to return all elements of array less than X using for loop approach.
function elementsLessThanX(arr, X) {
return arr.reduce((acc, curr) => {
if (curr < X) {
acc.push(curr);
}
return acc;
}, []);
}
const arr = [1, 3, 5, 7, 9];
const X = 6;
console.log(
"Elements less than", X, ":", elementsLessThanX(arr, X));
Output
Elements less than 6 : [ 1, 3, 5 ]
Time complexity: O(n)
Space complexity: O(n)
JavaScript Program to Return all Elements of Array Less than X
We will return all elements of an array that are less than a given value X in JavaScript. Given an array arr and number n and the task is to write a function that returns an array whose items are smaller than n.
Example:
Input array = [ 1 , 2, 3 , 4 , 5 , 6 , 7 , 8 , 9] X = 6
Output: [ 1 , 2 , 3 , 4 , 5]
Table of Content
- Using Filter Method
- Using for loop
- Using Array Reduce Method
- Using Array Iteration Method
Contact Us