Different ways of sorting array in Typescript

Angular Jun 26, 2019

What to expect

In this Typescript tutorial, we will see How we can sort arrays in typescript in
a typed manner

by the end of this small Typescript tutorial, you will know

How array sort works in typescript
Use of readonly array
sort function
return type
case sensitive sortings
Comparer function

How array sort works in typescript

Let us see how we can sort an array in typescript. Suppose we have an array arr
mentioned below, and I want to sort it. The easiest way is the [].sort function.

Sort function return type

So the surprising part is that the sort function has actually manipulated our
original array. It does not return a new array. Instead, it reorders our
original array.

Use Of ReadOnly

Let’s have a close look at result again and try to log the original array.

Sometimes we actually don’t want to manipulate the original array. Rather, we
want it to return a new array and that’s where we slice the array before the
sort function.

Another way to avoid manipulating the original array is to use readonly arrays.
Read-only arrays come in action if we mark our array as read-only. We are not
allowed to call the functions which can manipulate them after that point.

Case sensitive sortings

When we call the sort function, we are sorting the array in alphabetical order.
However, the default method of sorting is case sensitive. This means that It
first sorts alphabetically all the capital letters [A-Z], and only after that
has finished, it sorts the lower case letters [a-z]. We can see this in the
above example. Even though ‘a’ comes before ‘R’, the ordering of the new array
starts with ‘React’, since it is capitalized, and is followed by ‘angular’ and
‘vue’. This is something to keep in mind, if we want to sort the list
alphabetically. It may be worthwhile to convert all the characters in a string
to lowercase first.

Comparer function in sort function

Now the above code will work if the array element types are strings. But for
complex objects, there is a different approach. Let’s say we have an array of
objects and we want to sort on a specific property. Then in that case we will
have to pass a parameter to the sort function which is a function which accepts
two things. The first one is the first value of the array and the next is the
next value in that array and then we can return a.[specificproperty] —
b.[specificproperty]. Let’s an example of this:


Arrays sort function rearranges the array and returns the same array. It does
not returns a new array. It is case sensitive so capital letters will be sorted
before the lower case letters. For complex objects, we need to pass a comparer
method in which we can sort the array by a specific property.