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

1 Answer

0 votes
function CompareFunction(string1, string2) {
    if (string1.length == string2.length) {
        return parseInt(string1) - parseInt(string2);
    }
    else {
            return string1.length - string2.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:
 
0
2
4
6
7
8
9
55

*/

 



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

Related questions

...