Kit-Kat array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a natural number, num, as the first argument and two natural numbers m and n as the second and third argument. The task of our function is to return an array that contains all natural numbers from 1 to num (including num) in increasing order.

But if any number is a multiple of m, we should replace it by 'kit' string,

  • if any number is a multiple of n, we should replace it by 'kat', and

  • if any number is a multiple of both m and n it should be replaced by string 'kitkat'

Example

The code for this will be −

 Live Demo

const num = 50;
const m = 5, n = 6;
const kitKat = (num = 1, m = 1, n = 1) => {
   const res = [];
   for(let i = 1; i <= num; i++){
      if(i % m === 0 && i % n === 0){
         res.push('kitkat');
      }else if(i % m === 0){
         res.push('kit');
      }else if(i % n === 0){
         res.push('kat');
      }else{
         res.push(i);
      };
   };
   return res;
};
console.log(kitKat(num, m, n));

Output

And the output in the console will be −

[
   1, 2, 3, 4, 'kit',
   'kat', 7, 8, 9, 'kit',
   11, 'kat', 13, 14, 'kit',
   16, 17, 'kat', 19, 'kit',
   21, 22, 23, 'kat', 'kit',
   26, 27, 28, 29, 'kitkat',
   31, 32, 33, 34, 'kit',
   'kat', 37, 38, 39, 'kit',
   41, 'kat', 43, 44, 'kit',
   46, 47, 'kat', 49, 'kit'
]
raja
Updated on 03-Mar-2021 08:34:54

Advertisements