What is array.sort() in TypeScript?

Overview

The sort() method in TypeScript sorts the elements for an array and returns the sorted array. By default, it sorts an array in ascending order.

Syntax

array.sort()
array.sort(function)
Syntax for sorting an array in TypeScript

Parameters

  • array: This is the array that we want to sort.
  • function: This is the function we want to use to specify the sort order.

Return value

The value returned is a sorted array.

Example

// 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"]
let randomValues : Array<string | number | boolean> = ["one",1, "two", 2, 56, true]
// sort the arrays
console.log(names.sort())
console.log(numbers.sort())
console.log(cars.sort())
console.log(randomValues.sort())

Explanation

  • Lines 2–6: We create some arrays.
  • Lines 9–12: With the sort() method, we sort the arrays and print the results to the console screen.

Example: Using a function

// create an array
let numbers = [12, 34, 5, 0.9]
// sort the array using a function
numbers.sort(function(a, b){
return b - a; // sort in descending order
})
// print sorted array
console.log(numbers)

Explanation

  • Line 2: We create an array.
  • Line 5: We use the sort() method, with a function to sort the array in descending order.
  • Line 6: We ensure that return value is the one greater than all elements in the array.
  • Line 10: We print the sorted array to the console.

Free Resources