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

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

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.

Javascript

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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Define a Generic Type for an Array in TypeScript ? How to Define a Generic Type for an Array in TypeScript ?
Typescript Generic Type Array Typescript Generic Type Array
How to find Objects that Contain the same Elements from Arrays in Another Object ? How to find Objects that Contain the same Elements from Arrays in Another Object ?
How to filter Nested Array using Key in JavaScript ? How to filter Nested Array using Key in JavaScript ?
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ? How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12