How to sort an array of numeric strings in descending order with Node.js

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", "2", "4"];
  
arr.sort(CompareFunction);
  
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
  
  
  
  
/*
run:
  
55
9
8
7
6
4
2
0
 
*/

 



answered Sep 3, 2022 by avibootz

Related questions

...