How to sort the digits of a number in descending order with JavaScript

3 Answers

0 votes
let n = 38275;
let s = n.toString();

let arr = s.split('');
arr.sort();
arr.reverse();
s = arr.join('');

n = parseInt(s, 10);
 
console.log(n);

 
 
/*
run:
 
87532
 
*/

 



answered Mar 28, 2021 by avibootz
0 votes
function sortNumberDescending(num) {
	return Number(num.toString().split('').sort((a, b) => b - a).join(''));
}

let n = 38275;

n = sortNumberDescending(n)
  
console.log(n);
 
  
  
  
/*
run:
  
87532
  
*/

 



answered Jan 19, 2024 by avibootz
0 votes
function sortNumberDescending(num) {
	return parseInt(num.toString().split('').sort().reverse().join(''));
}

let n = 398275;

n = sortNumberDescending(n)
  
console.log(n);
 
  
  
  
/*
run:
  
987532
  
*/

 



answered Jan 19, 2024 by avibootz

Related questions

1 answer 113 views
1 answer 113 views
1 answer 109 views
3 answers 193 views
1 answer 133 views
1 answer 172 views
...