How to sort an array of numeric strings in descending order with JavaScript

1 Answer

0 votes
function CompareFunction(string1, string2) {
    if (string1.length == string2.length) {
        return parseInt(string2) - parseInt(string1);
    }
    else {
            return string2.length - string1.length;
        }
}
  
 
const arr = ["7", "0", "55", "8", "9", "6"];
  
arr.sort(CompareFunction);
  
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
  
  
  
  
/*
run:
  
"55"
"9"
"8"
"7"
"6"
"0"
 
*/

 

 



answered Sep 3, 2022 by avibootz
edited Sep 3, 2022 by avibootz
...