Languages
[Edit]
EN

TypeScript - compare strings

0 points
Created by:
Brandy-Mccabe
754

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

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

console.log( 'a'.localeCompare('a') );  //  0   // aab is equal to aab
console.log( 'a'.localeCompare('b') );  // -1   // a is before b
console.log( 'b'.localeCompare('a') );  // +1   // b is after a

console.log( 'aab'.localeCompare('aab') );  //  0   // aab is equal to aab
console.log( 'aac'.localeCompare('aaa') );  // +1   // aac is after aaa
console.log( '123'.localeCompare('321') );  // -1   // 123 is before 321

2. Compare with comparators example

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

console.log( 'a' == 'a' );  // true
console.log( 'a' < 'b'  );  // true
console.log( 'b' > 'a'  );  // true

console.log( 'aab' == 'aab' );  // true
console.log( 'aac' > 'aaa'  );  // true
console.log( '123' < '321'  );  // true

console.log( 'a' < 'a' );  // false
console.log( 'a' < 'b' );  // true
console.log( 'b' < 'a' );  // false

console.log( 'aab' > 'aab' );  // false
console.log( 'aac' > 'aaa' );  // true
console.log( '123' > '321' );  // false

3. Custom compare method example

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.

const compareStrings = (a: string, b: string): -1 | 1 | 0 => {
    if (a < b) return -1;
    if (a > b) return +1;
    return 0;
};


// Usage example:

console.log(compareStrings('a', 'a'));  //  0   // aab is equal to aab
console.log(compareStrings('a', 'b'));  // -1   // a is before b
console.log(compareStrings('b', 'a'));  // +1   // b is after a

console.log(compareStrings('aab', 'aab'));  //  0   // aab is equal to aab
console.log(compareStrings('aac', 'aaa'));  // +1   // aac is after aaa
console.log(compareStrings('123', '321'));  // -1   // 123 is before 321

4. Sorting array of objects example

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.

type FieldType = boolean | number | string | Date;

const compareValues = (a: FieldType, b: FieldType): number => {
    if (a < b) return -1;
    if (a > b) return +1;
    return 0;
};

// T is array item type
// F is T[columnName] type
const sortArray = <T extends unknown, F extends keyof T> (
    array: T[],
    columnName: F,
    compareValues: (a: T[F], b: T[F]) => number
): T[] => {
    return array.sort((a: T, b: T) => compareValues(a[columnName], b[columnName]));
};


// Usage example:

interface User {
    name: string;
    age: number;
    joinedAt: Date;
}

const users: User[] = [
    {name: 'Chris', age: 30, joinedAt: new Date(2019, 1,  1)},
    {name: 'Adel',  age: 26, joinedAt: new Date(2010, 7, 23)},
    {name: 'Kate',  age: 21, joinedAt: new Date(2020, 5, 15)},
];

const columnName: keyof User = 'joinedAt';

sortArray(users, columnName, compareValues);

for (let i = 0; i < users.length; ++i) {
    const entry: User = users[i];
    console.log(entry.name + '\t' + entry.age + '\t' + entry.joinedAt);
}

Output:

Adel    26      Mon Aug 23 2010 00:00:00 GMT+0200 (Central European Summer Time)
Chris   30      Fri Feb 01 2019 00:00:00 GMT+0100 (Central European Standard Time)
Kate    21      Mon Jun 15 2020 00:00:00 GMT+0200 (Central European Summer Time) 

Alternative titles

  1. TypeScript - compare strings (e. g. for sorting / ordering)
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