Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Returning number with increasing digits. in JavaScript
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.
Problem
Given a number, we need to arrange its digits in descending order to form the largest possible number from those digits.
Solution
The approach is to convert the number to a string, split it into individual digits, sort them in descending order, and then convert back to a number.
Example
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
7654322
How It Works
The function follows these steps:
-
Convert to string:
String(num)converts the number to a string to access individual digits -
Split into array:
split('')creates an array of digit characters -
Sort descending:
sort((a, b) => +b - +a)sorts digits from highest to lowest -
Join back:
join('')combines the sorted digits into a string -
Convert to number:
Number(newStr)converts the final string back to a number
Alternative Approach
Here's a more concise version using method chaining:
const arrangeInDescendingShort = (num) => {
return Number(
String(num)
.split('')
.sort((a, b) => b - a)
.join('')
);
};
console.log(arrangeInDescendingShort(9876543210));
console.log(arrangeInDescendingShort(1234));
console.log(arrangeInDescendingShort(505));
9876543210 4321 550
Edge Cases
The function handles various edge cases automatically:
console.log(arrangeInDescending(0)); // Single digit console.log(arrangeInDescending(1000)); // With zeros console.log(arrangeInDescending(987)); // Already sorted
0 1000 987
Conclusion
This solution efficiently rearranges digits in descending order by converting to string, sorting, and converting back to number. The approach handles all edge cases including zeros and single digits automatically.
