1// Numbers
2// When sorting numbers, you can use the compact comparison:
3
4var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];
5
6var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);
7// i.e. - rather than <.
8
9// Other Types
10// If you are comparing anything else, you'll need to convert the comparison into a number.
11
12var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];
13
14var sortedArray: string[] = stringArray.sort((n1,n2) => {
15 if (n1 > n2) {
16 return 1;
17 }
18
19 if (n1 < n2) {
20 return -1;
21 }
22
23 return 0;
24});
25// Objects
26// For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.
27
28var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];
29
30var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
31 if (n1.age > n2.age) {
32 return 1;
33 }
34
35 if (n1.age < n2.age) {
36 return -1;
37 }
38
39 return 0;
40});
1let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];
2
3let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }
4
5const sortedArray2:{key:number}[] = arr.sort(sortFn2);
6
1var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];
2
3var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);
1var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];
2
3var sortedArray: string[] = stringArray.sort((n1,n2) => {
4 if (n1 > n2) {
5 return 1;
6 }
7
8 if (n1 < n2) {
9 return -1;
10 }
11
12 return 0;
13});