create an array of numbers and sort them in javascript

To create an array of numbers in JavaScript, we can declare an array variable and assign it an array of numbers separated by commas enclosed in square brackets:

index.tsx
let numbers = [4, 2, 8, 1, 5];
31 chars
2 lines

To sort the array in ascending order, we can use the Array.prototype.sort() method with a compare function that subtracts the second value from the first value. This will sort the numbers in numerical order because the result of the subtraction will be negative if the first value is smaller and positive if it's larger:

index.tsx
numbers.sort((a, b) => a - b);
31 chars
2 lines

To sort the array in descending order, we can reverse the order of subtraction:

index.tsx
numbers.sort((a, b) => b - a);
31 chars
2 lines

The sorted array will now be:

index.tsx
[1, 2, 4, 5, 8]
16 chars
2 lines

gistlibby LogSnag