Reversed array of digits from number using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number. Our function should first reverse the number and then split the reversed number into digits and return that splitted array of digits.

Input

const num = 1234567;

Output

const output = [7, 6, 5, 4, 3, 2, 1];

Because the reverse number is 7654321

Example

Following is the code −

 Live Demo

const num = 1234567;
const reverseAndSplit = (num = 1) => {
   const numStr = String(num);
   const arr = numStr.split('');
   arr.reverse();
   return arr.map(el => {
      return Number(el);
   });
};
console.log(reverseAndSplit(num));

Output

[7, 6, 5, 4, 3, 2, 1]
raja
Published on 17-Apr-2021 12:02:58
Advertisements