Is the digit divisible by the previous digit of the number in JavaScript

Problem

We need to write a JavaScript function that takes a number and checks if each digit is divisible by the digit on its left. The function returns an array of booleans, where the first element is always false since there's no digit before the first one.

Example

Let's check the number 73312 digit by digit:

const num = 73312;
const divisibleByPrevious = (n = 1) => {
    const str = n.toString();
    const arr = [false];
    
    for(let i = 1; i < str.length; ++i){
        if(str[i] % str[i-1] === 0){
            arr.push(true);
        } else {
            arr.push(false);
        }
    }
    
    return arr;
};

console.log(divisibleByPrevious(num));

Output

[ false, false, true, false, true ]

How It Works

For the number 73312, the function checks:

  • Position 0 (7): Always false - no previous digit
  • Position 1 (3): 3 ÷ 7 = not divisible ? false
  • Position 2 (3): 3 ÷ 3 = divisible ? true
  • Position 3 (1): 1 ÷ 3 = not divisible ? false
  • Position 4 (2): 2 ÷ 1 = divisible ? true

Additional Example

Let's test with another number:

console.log(divisibleByPrevious(1248));
console.log(divisibleByPrevious(936));
[ false, true, true, true ]
[ false, true, true, true ]

Conclusion

This function efficiently converts the number to a string and uses the modulo operator to check divisibility between consecutive digits. The result is an array of boolean values indicating divisibility relationships.

Updated on: 2026-03-15T23:19:00+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements