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.
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.
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. |
Array.sort() returns value of type this
.
The sort() method can be used without a compare function to sort an array of strings in ascending order.
For example,
arr
with string values ['banana', 'apple', 'cherry'].sort()
to sort the array in ascending order.arr
to the console.const arr = ['banana', 'apple', 'cherry'];
arr.sort();
console.log(arr);
['apple', 'banana', 'cherry']
The sort() method can be used with a compare function to sort an array of numbers in ascending order.
For example,
arr
with numeric values [40, 100, 1, 5, 25, 10].sort(compareFn)
to sort the array using the compare function.arr
to the console.const arr = [40, 100, 1, 5, 25, 10];
arr.sort((a, b) => a - b);
console.log(arr);
[1, 5, 10, 25, 40, 100]
The sort() method can be used with a compare function to sort an array of objects based on a specific property.
For example,
arr
with objects containing name
and age
properties.age
property in ascending order.sort(compareFn)
to sort the array using the compare function.arr
to the console.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);
[{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Jim', age: 35 }]
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.