To sort an array in TypeScript, you can use the built-in sort()
method.
In this example,
numbers
with values 5, 2, 8, 1, 6.sort()
method on the array to sort it in ascending order.sort()
method sorts the array elements in ascending order based on their UTF-16 code units values.numbers
to the console.let numbers: number[] = [5, 2, 8, 1, 6];
numbers.sort((a, b) => a - b);
console.log("Sorted array in ascending order: ", numbers);
Sorted array in ascending order: [ 1, 2, 5, 6, 8 ]
In this example,
numbers
with values 5, 2, 8, 1, 6.sort()
method on the array with a custom comparator to sort it in descending order.numbers
to the console.let numbers: number[] = [5, 2, 8, 1, 6];
numbers.sort((a, b) => b - a);
console.log("Sorted array in descending order: ", numbers);
Sorted array in descending order: [ 8, 6, 5, 2, 1 ]
In this tutorial, we learned How to Sort an Array in TypeScript language with well detailed examples.