JavaScript Code

How to sort characters in string in descending order in JavaScript?

Sort characters in a string in descending order

Given a string, arrange the characters of the given string in descending or decreasing order, using JavaScript.


To arrange the characters of a given string in descending order using JavaScript, first split the string into character array, sort the array in ascending order, reverse the array, and join the array.

String.split("") splits the string into array of characters. Observe that we passed an empty string as argument to split() method.

Array.sort() sorts the array of characters in ascending order.

Array.reverse() reverses the array of characters, and the order of characters become descending.

Array.join("") joins the array of characters into a string. Again, observe that we have passed an empty string to join() method. Empty string is used as delimiter between the items of the array while joining.

All these methods can be joining together via chaining mechanism. The string str can be reversed using the following expression.



1. Given a string in str. Reverse the string str .

let str = 'hello world';
let output = str.split("").sort().reverse().join("");