To sort an array in TypeScript, you can use the sort()
method that is built into JavaScript. The sort()
method sorts the elements of an array in place and returns the sorted array.
Here is an example:
index.ts86 chars4 lines
In the example above, we have an array of numbers that we want to sort. We call the sort()
method on the array and it will sort the elements in place.
The sort()
method can also take a compare function that determines the order of the elements.
Here is an example where we use a compare function to sort an array of strings in reverse alphabetical order:
index.ts202 chars8 lines
In this example, we use a compare function that takes two strings a
and b
as input and returns a number. If a
is less than b
, we return 1, which tells sort()
to move a
to a higher index than b
. If a
is greater than b
, we return -1, which tells sort()
to move a
to a lower index than b
. If a
and b
are equal, we return 0, which tells sort()
to leave them in their current order.
gistlibby LogSnag