Today’s DevAdvent problem is an exercise in number ordering. But with an interesting variation: it requires you to break down a number and use its digits to get the highest possible number. In some ways it is related to the two previous problems (How To Get Min Or Max Of An Array In JavaScript And TypeScript and 5 Ways to Convert a Number to a String in JavaScript)
The problem
link to the Kata
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input: 42145
Output: 54421
Input: 145263
Output: 654321
Input: 123456789
Output: 987654321
My solution

The solution I propose is divided into 5 steps:
- Convert the number to a string (this is necessary because the number is not iterable)
const str: string = "" + n;
- Convert the string to an array of characters
const strArray: string[] = [...str];
- Sort the array of characters
const sortedArray: string[] = strArray.sort((a, b) => +b - +a);
- Join the array of characters
const arrayJoined: string = sortedArray.join("");
- Convert the string to a number
const result = +arrayJoined;
By putting the various pieces together I get this function
export function descendingOrder(n: number): number {
const str: string = "" + n;
const strArray: string[] = [...str];
const sortedArray: string[] = strArray.sort((a, b) => +b - +a);
const arrayJoined: string = sortedArray.join("");
return +arrayJoined;
}
I can write a more concise version by merging the various steps into one
export const descendingOrder = (x: number): number =>
+[...("" + x)].sort((a, b) => +b - +a).join("");
Starting from this version I can get the equivalent in JavaScript.
export const descendingOrder = (x) =>
+[...("" + x)].sort((a, b) => +b - +a).join("");
I’ll stop here for today. Today is the ninth anniversary of my first date with my wife. Enough coding for today. Time to spend the day with my bride.