Open In App

How to Sort a Numerical String in TypeScript ?

To sort numerical string in TypeScript, we could use localCompare method or convert numerical string to number.

Below are the approaches used to sort numerical string in TypeScript:



Approach 1: Using localeCompare

The localeCompare() is an inbuilt function in TypeScript that is used to get the number indicating whether a reference string comes before or after or is the same as the given string in sorted order. 



Syntax:

string.localeCompare( param ) 

Example: Here, In this example, we are using LocalCompare() method.




const numericalStrings: string[] =
    ["10", "3", "22", "5", "8"];
console.log("Before Sorting");
console.log(numericalStrings);
numericalStrings.sort((a, b) =>
    a.localeCompare(b, undefined, { numeric: true }));
console.log("After Sorting");
console.log(numericalStrings);

Output:

Before Sorting"
["10", "3", "22", "5", "8"]
After Sorting
["3", "5", "8", "10", "22"]

Approach 2: Converting to Numbers before sorting

Here, we convert the strings to numbers using Number() before sorting. The subtraction inside the sort function compares them numerically.

Syntax

numericalStrings.sort((a, b) => Number(a) - Number(b));

Example: Here, we are converting numerical string to numbers before sorting.




const numericalStrings: string[] = ["10", "3", "22", "5", "8"];
console.log("Before Sorting")
console.log(numericalStrings)
numericalStrings.sort((a, b) => Number(a) - Number(b));
console.log("After Sorting")
console.log(numericalStrings);

Output:

Before Sorting
"["10", "3", "22", "5", "8"]
After Sorting
["3", "5", "8", "10", "22"]

Article Tags :