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


Problem

We are required to write a JavaScript function that takes in a number and checks each digit if it is divisible by the digit on its left and returns an array of booleans.

The booleans should always start with false because there is no digit before the first one.

Example

Following is the code −

 Live Demo

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 ]

Updated on: 21-Apr-2021

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements