How to sort a string with digits and letters (digits before letters) in TypeScript

1 Answer

0 votes
function customSort(input: string): string {
    const chars: string[] = input.split('');

    chars.sort((a: string, b: string) => {
        if (!isNaN(Number(a)) && isNaN(Number(b))) return -1; // Digits before letters
        if (isNaN(Number(a)) && !isNaN(Number(b))) return 1; // Letters after digits
        return a.localeCompare(b);
    });

    return chars.join('');
}

const input: string = "d52ea4b3c1";
const sortedInput: string = customSort(input);

console.log("Custom sorted string:", sortedInput);



/*
run:

"Custom sorted string:",  "12345abcde" 

*/

 



answered May 27, 2025 by avibootz
...