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


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' ]

Updated on: 20-Apr-2021

48 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements