Languages
[Edit]
EN

TypeScript - compare strings

0 points
Created by:
Brandy-Mccabe
724

In this article, we're going to have a look at how to compare two strings when we want to sort them in TypeScript.

There are two approaches to do it:

  • String localeCompare method - that returns information which one should be first according to alphabet letters priority.
  • comparators like: <, >== or === - that return only true or false for compared strings,

The second approach requires at least two tests to know about compared strings priority.

In the below example you can see practical usage:

1. Compare with one method example

Edit

String localeCompare method returns -1, 0 or +1 value to inform which one should be first according to alphabet letters priority.

2. Compare with comparators example

Edit

With this approach, we need to make a few tests to know which one should be first.

3. Custom compare method example

Edit

In this section, we want to show how to write our own comparison method using operators.

Note: with this approach we are able to compare numbers, strings, dates and booleans without writing additional functions - so it can be easly used to sort data by any column, e.g. in last section with sorting array of objects.

4. Sorting array of objects example

Edit

The approach presented in this section is universal - can be used to sort columns with different types. Check the previous section (3. Custom compare method example) to see the simplest example.

Output:

Alternative titles

  1. TypeScript - compare strings (e. g. for sorting / ordering)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join