Reversed array of digits from number using JavaScript


Understanding how to reverse an array of digits from a number using JavaScript is a significant skill that empowers developers to manipulate and transform data with precision. In the realm of web development, the ability to reverse the order of digits in a number opens doors to a plethora of possibilities, enhancing algorithms, data processing, and user interactions. This article delves into the intricacies of reversing an array of digits from a number using JavaScript, unraveling the lesser-known techniques and methods that enable developers to efficiently manipulate numerical data. By mastering this technique, developers can unlock the potential to create efficient and elegant solutions for a wide range of numerical challenges.

Problem Statement

Design a JavaScript function that takes an integer number as input and returns an array containing the digits of the number in reverse order. The function should handle positive and negative numbers.

Sample Input −

12345

Sample Output −

[5, 4, 3, 2, 1] 

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Using Array Methods

  • Using a Loop

  • Using Recursion

  • Using Array Spread Operator and Splitting

  • Using Array.from() and Splitting

Method 1: Using Array Methods

Convert the number to a string, then use Array.from() to create an array by mapping each character to a number. Reverse the array using the reverse() method, and finally, return the reversed array.

Example

To convert a number to a reversed array of its digits, first convert the number to a string using String(number). Then, use Array.from() to convert the string into an array, with each element representing a digit. Apply the Number function as the mapping function to convert each string digit to a number. Finally, use the reverse() method to reverse the array's order and obtain the reversed array of digits.

function reverseArrayUsingArrayMethods(number) {
   const digits = Array.from(String(number), Number);
   return digits.reverse();
}
 
const number = 219280;
console.log(reverseArrayUsingArrayMethods(number));

Output

The following is the console output −

[ 0, 8, 2, 9, 1, 2 ]

Method 2: Using a Loop

To reverse a number, start by creating an empty array called "digits." Then, use a while loop to iterate until the number becomes zero. Within the loop, extract the last digit of the number using the modulus operator (%) and add it to the "digits" array. Next, update the number by dividing it by 10 and removing the decimal part using Math.floor(). Repeat this process until the number becomes zero. Finally, return the "digits" array, which now contains the reversed digits of the original number.

Example

To extract each digit from a number, a while loop is employed. The modulus operator % is utilized to obtain the last digit of the number, which is then appended to the digits array. Subsequently, the number is updated by dividing it by 10 and removing the decimal portion with Math.floor(number / 10). This iteration continues until the number reaches zero, indicating that all digits have been extracted and included in the digits array. Finally, the digits array is returned.

function reverseArrayUsingLoop(number) {
   const digits = [];
   while (number > 0) {
      const digit = number % 10;
      digits.push(digit);
      number = Math.floor(number / 10);
   }
   return digits;
}

const number = 219280;
console.log(reverseArrayUsingLoop(number));

Output

The following is the console output −

[ 0, 8, 2, 9, 1, 2 ]

Method 3: Using Recursion

The algorithm checks if the number is less than 10, returning an array with the number as a single element if true. Otherwise, it calculates the last digit using the modulus operator (%) and assigns it to a variable named "digit." The function is then called recursively with the remaining digits, obtained by dividing the number by 10 and removing the decimal part with Math.floor(). Using the concat() method, the digit is concatenated with the result of the recursive call to create an array with the reversed order of digits. Finally, the reversed array is returned.

Example

This recursive approach reverses an array of digits. If the number is less than 10, it returns an array with that digit. Otherwise, it calculates the last digit using number % 10 and stores it. The function recursively calls itself with the remaining digits obtained by dividing the number by 10. The result is concatenated with the digit using the concat() method, creating a reversed array. Finally, the reversed array is returned.

function reverseArrayUsingRecursion(number) {
   if (number < 10) {
   return [number];
   } else {
      const digit = number % 10;
      const remainingDigits = reverseArrayUsingRecursion(Math.floor(number / 10));
      return [digit].concat(remainingDigits);
   }
}

const number = 219280;
console.log(reverseArrayUsingRecursion(number));

Output

The following is the console output −

[ 0, 8, 2, 9, 1, 2 ]

Method 4: Using Array Spread Operator and Splitting

First, convert the number to a string and use the spread operator (...) to split it into an array of individual characters. Then, apply the map() method to convert each character from a string to a number using the Number() function. Reverse the array using the reverse() method and return the resulting reversed array.

Example

To convert a number to a reversed array of digits, this approach begins by converting the number to a string using String(number). The spread operator ... is then utilized to split the string into individual characters, creating an array of strings representing each digit. The map() method is applied to the array, employing the Number function as the mapping function to convert each string digit to a number. Lastly, the digits array is reversed using the reverse() method, and the resulting reversed array is returned.

function reverseArrayUsingSpreadOperator(number) {
   const digits = [...String(number)].map(Number);
   return digits.reverse();
}

const number = 219280;
console.log(reverseArrayUsingSpreadOperator(number));

Output

The following is the console output −

[ 0, 8, 2, 9, 1, 2 ]

Method 5: Using Array.from() and Splitting

First, convert the number to a string. Then, utilize the Array.from() method, providing the string and a mapping function as parameters. Within the mapping function, use Number() to convert each string digit to a number. This will generate an array containing the converted numbers. To reverse the order of the array, apply the reverse() method. Finally, return the reversed array.

Example

In this alternative approach, the Array.from() method replaces the spread operator to convert the string number into an array, assigning each digit to an element. The Array.from() method employs a mapping function that converts each string digit to a number using Number(digit). The resulting array of numbers is stored in the digits variable. Ultimately, the reverse() method is applied to the digits array, reversing its order, and the reversed array is returned.

function reverseArrayUsingArrayFrom(number) {
const digits = Array.from(String(number), (digit) => Number(digit));
return digits.reverse();
}

const number = 219280;
console.log(reverseArrayUsingArrayFrom(number));

Output

The following is the console output −

[ 0, 8, 2, 9, 1, 2 ]

Conclusion

In conclusion, the process of reversing an array of digits from a number using JavaScript can be accomplished with felicity, providing an elegant solution to an otherwise intricate problem. By harnessing the power of mathematical operations and leveraging the versatility of JavaScript's array manipulation capabilities, one can transpose the order of digits in a number swiftly and effortlessly. This idiosyncratic technique holds tremendous potential for enhancing various computational tasks, particularly those that necessitate a reversed representation of numerical data. In a world where innovation hinges upon unorthodox methodologies, this unconventional approach serves as a testament to the boundless creativity and ingenuity of JavaScript programmers.

Updated on: 04-Aug-2023

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements