EN
TypeScript - sort array
0 points
In TypeScript it is possible to sort array in following ways.
In this example numbers are sorted from smallest to biggest - Array
sort
(Array.prototype.sort
) method with ascending ordering has been used.
xxxxxxxxxx
1
const array: number[] = [5, 2, 3, 1, 4];
2
array.sort();
3
4
console.log(array);
Output:
xxxxxxxxxx
1
[ 1, 2, 3, 4, 5 ]
In this example numbers are sorted from smallest to biggest with compare function.
xxxxxxxxxx
1
const array: number[] = [5, 2, 3, 1, 4];
2
3
array.sort(function (a, b) {
4
return a - b;
5
});
6
7
console.log(array);
Output:
xxxxxxxxxx
1
[ 1, 2, 3, 4, 5 ]
In this example numbers are sorted from biggest to smallest - in this case compare function is necessary.
xxxxxxxxxx
1
const array: number[] = [5, 2, 3, 1, 4];
2
3
array.sort(function (a, b) {
4
return b - a;
5
});
6
7
console.log(array);
Output:
xxxxxxxxxx
1
[ 5, 4, 3, 2, 1 ]
In this example numbers are sorted from biggest to smallest - in this case reverse function has been used.
xxxxxxxxxx
1
const array: number[] = [5, 2, 3, 1, 4];
2
3
const result = array.sort().reverse();
4
5
console.log(result);
Output:
xxxxxxxxxx
1
[ 5, 4, 3, 2, 1 ]