How to usethe reduce method in Javascript

Here, we will be using the reduce method to iterate over the elements and find the factors of the input number specific to the variable. This uses the ES6 feature for iteration and stores the output factors in the array. Then we print these factors in the console.

Example: This example implements the above-approach.

Javascript
let n = 12;
[...Array(n + 1).keys()].reduce(
    (_, i) => {
        if (i !== 0 && n % i === 0) {
            console.log(i);
        }
    }
);

Output
1
2
3
4
6
12

JavaScript Program to Find the Factors of a Number

We have given the input number and we need to find all the factors of that number. Factors of the number are nothing but the numbers that divide the original input number evenly with the remainder of 0. Below we have added the example for better understanding:

Example:

Input: n = 10
Output: 1 2 5 10
Input: n = 12
Output: 1 2 3 4 6 12

Table of Content

  • Using For Loop
  • Using Spread Operator
  • Using the reduce method
  • Using the map method

Similar Reads

Approach 1: Using For Loop

...

Approach 2: Using Spread Operator

Here, we are finding the factors of the input number by using the simple and traditional method that is for loop. We are firstly iterating through the values of 1 to the input number (12). Then using the if condition, we are checking whether the n is exactly divisible or not. This is the simplest method to find the factors of the input number....

Approach 3: Using the reduce method

Here we are using the Spread operator of JavaScript and the keys method to find the factors of the input number given by the user. The factors are stored in the array and printed using the console.log function....

Approach 4: Using the map method

Here, we will be using the reduce method to iterate over the elements and find the factors of the input number specific to the variable. This uses the ES6 feature for iteration and stores the output factors in the array. Then we print these factors in the console....

Approach 5: Using a While Loop

Here, we are using the map method which creates an array by calling the specific function on each of the elements present in the parent array. Mostly, the map method is used to iterate through the array and call function on every element of the array....

Contact Us