sort the following list of numbers: [1, 3, 4, 2, 5] in typescript

To sort the given array of numbers in typescript, we can use the sort function available in the Array object. Here is how it can be done:

index.ts
const numbers: number[] = [1, 3, 4, 2, 5];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]
115 chars
4 lines

The sort function takes a compare function as an optional parameter that determines the sorting order. The compare function takes two arguments (a and b) and returns a negative number if a should come before b, a positive number if b should come before a, and 0 if their order does not matter.

In this case, we use the arrow function (a, b) => a - b to sort the array in ascending order. For descending order, we can simply use (a, b) => b - a.

related categories

gistlibby LogSnag