How to sort an array of numeric strings in ascending order with TypeScript

1 Answer

0 votes
function CompareFunction(string1 : string, string2 : string) {
    if (string1.length == string2.length) {
        return parseInt(string1) - parseInt(string2);
    }
    else {
            return string1.length - string2.length;
        }
}
 

const arr : string[] = ["7", "0", "55", "8", "9", "6", "3"];
 
arr.sort(CompareFunction);
 
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
 
 
 
 
/*
run:
 
"0" 
"3" 
"6" 
"7" 
"8" 
"9" 
"55" 

*/

 



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

Related questions

...