sort an array in typescript

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.ts
let arr: number[] = [4, 2, 5, 1, 3];
arr.sort();
console.log(arr); // [1, 2, 3, 4, 5]
86 chars
4 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.ts
let arr: string[] = ["apple", "banana", "cherry", "date"];
arr.sort((a, b) => {
  if (a < b) return 1;
  if (a > b) return -1;
  return 0;
});
console.log(arr); // ["date", "cherry", "banana", "apple"]
202 chars
8 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