Returning number with increasing digits. in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 17-Apr-2021 11:36:27
Advertisements