EN
TypeScript - sort array of integers
0 points
In this article, we would like to show you how to sort an array of integers in TypeScript.
Quick solution:
xxxxxxxxxx
1
const numbers: number[] = [10, 2, 5];
2
3
numbers.sort((x: number, y: number): number => {
4
return x - y;
5
});
6
7
console.log(numbers); // [ 2, 5, 10 ]
In this example, we use sort()
method to sort the array of integers. However, the sort()
method sorts elements alphabetically, so we need to specify an additional function inside which handles numeric sorts.
xxxxxxxxxx
1
const numbers: number[] = [10, 2, 5, 1, 3];
2
3
numbers.sort((x: number, y: number): number => {
4
return x - y;
5
});
6
7
console.log(numbers);
Output:
xxxxxxxxxx
1
[ 1, 2, 3, 5, 10 ]