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