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

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: 2021-04-20T07:06:13+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements