For today’s algorithm, we are going to write a function called `findDigits`

that will take in an integer `n`

as input.

When finding a number that is a divisor of another number in JavaScript you use the modulo operator. The modulo operator returns the division remainder. If something is equally divisible then the remainder will be 0. You are given an integer `n`

and the goal of the function is to take each digit within that full integer and determine if that digit is a divisor of `n`

. Return the number of digits that are divisors of `n`

. Let’s use an example.

`let n = 426;`

Our variable `n`

is 426 and the digits that make up the number are **4**, **2**, and **6**.

Let’s divide 426 by each of those digits and see which digit is a divisor of 426.

`426 / 4 = 106.5 // not a whole number, therefore not a divisor`

426 / 2 = 213

426 / 6 = 71

We see that two digits, **2** and **6** are divisors of 426, therefore, the function will output 2.

Let’s turn this into code. We create our variables:

`let digitArray = (n + "").split('');`

let divisors = [];

Our `digitArray`

variable carries our input and splits it into individual digits and puts them into an array. We first convert the number into a string by concatenating it to an empty string. Then we use the `split()`

method along with using the `''`

as a separator so we can split our string into individual characters.

Our `divisors`

variable will carry all the numbers that are divisors of `n`

in an array. It is currently empty.

Now we loop through our `digitArray`

array:

`for(let i = 0; i < digitArray.length; i++){`

let num = digitArray[i]*1;

if(n % num == 0){

divisors.push(num)

}

}

The characters within the digitArray are strings so we quickly convert them to integers by multiplying them by 1. We assign that value into the num variable for use in our if-statement conditional.

We check if the individual digit is a divisor of `n`

. We use the modulo operator. If the remainder is 0 then it is a divisor. We put that digit into our `divisors`

array.

Finally, we return the number of digits in `n`

that are divisors of `n`

by returning the length of the `divisors`

array.

`return divisors.length;`

Here is the full code:

`function findDigits(n) {`

let digitArray = (n + "").split('');

let divisors = [];

for(let i = 0; i < digitArray.length; i++){

let num = digitArray[i]*1;

if(n % num == 0){

divisors.push(num)

}

}

return divisors.length;

}

If you found this algorithm helpful or useful, check out my other JavaScript algorithm solution articles: