How to use Array Reduce() Method In Javascript

In this approach, Using the reduce() method, reverse the digits of a number. Convert the number to an array of its digits, then employ the reduce() function with a spread operator to reverse the order.

Syntax:

function reverseFunction(num) {
let digits = Array.from(String(num), Number);
let reversedArray = digits.reduce((acc, digit) =>
[digit, ...acc], []);
return parseInt(reversedArray.join(''));
};

Example: In this example we are using above explained approach.

Javascript




function reverseFunction(num) {
    let digits = Array.from(String(num), Number);
    let reversedArray = digits.reduce((acc, digit) =>
        [digit, ...acc], []);
    return parseInt(reversedArray.join(''));
}
 
let num = 123456789;
let reversedNum = reverseFunction(num);
 
console.log(reversedNum);


Output

987654321

JavaScript Program to Reverse Digits of a Number

In this article, we are going to learn about Reverse Number Programs in JavaScript. A reverse number in JavaScript involves reversing the digits of a given number. It’s done by manipulating the digit’s order, resulting in the number’s reversed form.

There are several methods that can be used to Reverse the Numbers by using JavaScript, which is listed below:

Table of Content

  • Using String Reversal
  • Using Array Reduce() Method
  • Using String Iteration
  • Using Recursion

Similar Reads

Using String Reversal

In this approach, we are using string reversal, converting a number to a string, reverse it using split(”).reverse().join(”), and convert back to a number....

Using Array Reduce() Method

...

Using String Iteration

In this approach, Using the reduce() method, reverse the digits of a number. Convert the number to an array of its digits, then employ the reduce() function with a spread operator to reverse the order....

Using Recursion

...

Contact Us