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.

JavaScript
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 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

Similar Reads

Using Filter Method

This utilizes the built-in filter method to create a new array containing elements less than X based on a provided condition function....

Using for loop

It iterates through the array and selectively adds elements less than X into a new array, offering control over the filtering process with explicit looping....

Using Array Reduce Method

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....

Using Array Iteration Method

It utilizes forEach to iterate through the array and selectively adds elements less than X into a new array, offering simplicity and readability for the filtering operation....

Contact Us