How to usethe map method in Javascript
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.
Example: This example implements the above-approach.
let n = 12;
let fact = [...Array(n + 1).keys()]
.map((i) => {
if (n % i === 0) {
return i;
}
})
.filter((i) => i !== undefined);
console.log(fact);
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