Cutting off number at each digit to construct an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number. Our function should return an array of strings containing the number cut off at each digit.

Example

Following is the code −

 Live Demo

const num = 246;
const cutOffEach = (num = 1) => {
   const str = String(num);
   const res = [];
   let temp = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      temp += el;
      res.push(temp);
   };
   return res;
};
console.log(cutOffEach(num));

Output

Following is the console output −

[ '2', '24', '246' ]
raja
Published on 20-Apr-2021 07:04:06
Advertisements