How to sort an array of strings where each string represents a decimal number in TypeScript

1 Answer

0 votes
// Comparator function to sort strings as decimal numbers
function compareAsDecimal(a: string, b: string): number {
    // Convert strings to numbers for comparison
    const numA: number = parseFloat(a);
    const numB: number = parseFloat(b);
    
    return numA - numB; 
}

// Input array of strings
const numbers: string[] = ["12.3", "5.6", "789.1", "3.14", "456.0", "0", "0.01", "4.0"];

// Sort the array using the custom comparator
numbers.sort(compareAsDecimal);

console.log("Sorted array of decimal strings:");
console.log(numbers.join("  "));



/*
run:

"Sorted array of decimal strings:" 
"0  0.01  3.14  4.0  5.6  12.3  456.0  789.1" 

*/

 



answered Sep 1 by avibootz
edited Sep 1 by avibootz
...