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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources