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): thisThis sort() method of Array sorts the elements of an array in place and returns the sorted array.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
compareFn | optional | Specifies 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,
- Create an array
arrwith string values ['banana', 'apple', 'cherry']. - Use
sort()to sort the array in ascending order. - Log the sorted array
arrto 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,
- Create an array
arrwith numeric values [40, 100, 1, 5, 25, 10]. - Define a compare function to sort numbers in ascending order.
- Use
sort(compareFn)to sort the array using the compare function. - Log the sorted array
arrto 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,
- Create an array
arrwith objects containingnameandageproperties. - Define a compare function to sort the objects by the
ageproperty in ascending order. - Use
sort(compareFn)to sort the array using the compare function. - Log the sorted array
arrto 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.