TypeScript Array sort()
Syntax & Examples

Array.sort() method

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is built upon converting the elements into strings and comparing their sequences of UTF-16 code unit values.


Syntax of Array.sort()

The syntax of Array.sort() method is:

sort(compareFn?: function): this

This sort() method of Array sorts the elements of an array in place and returns the sorted array.

Parameters

ParameterOptional/RequiredDescription
compareFnoptionalSpecifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

Return Type

Array.sort() returns value of type this.



✐ Examples

1 Using sort() without a compare function

The sort() method can be used without a compare function to sort an array of strings in ascending order.

For example,

  1. Create an array arr with string values ['banana', 'apple', 'cherry'].
  2. Use sort() to sort the array in ascending order.
  3. Log the sorted array arr to the console.

TypeScript Program

const arr = ['banana', 'apple', 'cherry'];
arr.sort();
console.log(arr);

Output

['apple', 'banana', 'cherry']

2 Using sort() with a compare function to sort numbers

The sort() method can be used with a compare function to sort an array of numbers in ascending order.

For example,

  1. Create an array arr with numeric values [40, 100, 1, 5, 25, 10].
  2. Define a compare function to sort numbers in ascending order.
  3. Use sort(compareFn) to sort the array using the compare function.
  4. Log the sorted array arr to the console.

TypeScript Program

const arr = [40, 100, 1, 5, 25, 10];
arr.sort((a, b) => a - b);
console.log(arr);

Output

[1, 5, 10, 25, 40, 100]

3 Using sort() with a compare function to sort objects

The sort() method can be used with a compare function to sort an array of objects based on a specific property.

For example,

  1. Create an array arr with objects containing name and age properties.
  2. Define a compare function to sort the objects by the age property in ascending order.
  3. Use sort(compareFn) to sort the array using the compare function.
  4. Log the sorted array arr to the console.

TypeScript Program

const arr = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
arr.sort((a, b) => a.age - b.age);
console.log(arr);

Output

[{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Jim', age: 35 }]

Summary

In this TypeScript tutorial, we learned about sort() method of Array: the syntax and few working examples with output and detailed explanation for each example.