How to uselocaleCompare in Typescript

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.

Javascript




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"]

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:

Table of Content

  • Using localeCompare
  • Converting to Numbers before sorting

Similar Reads

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....

Approach 2: Converting to Numbers before sorting

...