How to sort an array in TypeScript

Overview

In TypeScript, we use the sort() method for sorting an array. This means that we want the elements of an array to be displayed in either ascending or descending order using number values and string values.

Syntax

The syntax for the sort() method is given below:

array.sort(compareFunction)
Sort an array in TypeScript

Parameters

compareFunction: This is an optional function that defines how elements should be sorted.

Return value

Elements are returned in a lexicographical way.

Code

Here are some example use cases of the sort() method.

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>;
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
// sort the arrays and print results
console.log(names.sort())
console.log(numbers.sort())
console.log(cars.sort())

Explanation

  • Lines 2–5: Create some arrays in TypeScript.
  • Lines 8–10: Sort the arrays and print their results.

Free Resources