You can split the String on ""
and map it to convert each item to a number. Then you can use Array.prototype.sort
to put it in descending order. If you want it as a String you can join it on ""
.
var str = "92345";
var numStr = str.split('').map(function(item) {
return +item;
});
var orderedArr = numStr.sort(function(a,b){
return b-a;
});
var orderedStr = orderedArr.join("");
console.log(orderedArr);
console.log(orderedStr);
A shorter way would be to use the unary operator to convert the String to a number, split it on ""
, sort it, and join it on ""
.
var str = "91785";
function orderDesc(str){
return +str.split('').sort((a,b)=>b-a).join('');
}
console.log(orderDesc(str));
2
solved Break the string and arrange it in highest order