Returning number with increasing digits. in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should return it with its digits in descending order. Essentially, we should rearrange the digits to create the highest possible number.

Example

Following is the code −

 Live Demo

const num = 5423267;
const arrangeInDescending = (num = 1) => {
   const str = String(num);
   const arr = str.split('');
   arr.sort((a, b) => {
      return +b - +a;
   });
   const newStr = arr.join('');
   const res = Number(newStr);
   return res;
};
console.log(arrangeInDescending(num));

Output

Following is the console output −

7654322

Updated on: 17-Apr-2021

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements