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

To sort the given list of numbers in ascending order, we can use the built-in sort method of arrays in javascript. Here's the code:

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

The sort method takes an optional function as an argument, which is used to compare the elements of the array. In this case, we are using an arrow function to subtract each element from the next element, which will result in a sorted array in ascending order.

We can also use the reverse method to sort the array in descending order:

index.tsx
numbers.sort((a, b) => b - a);
console.log(numbers); // [5, 4, 3, 2, 1]
72 chars
3 lines

Note that the sort method modifies the original array in place, which means that it will no longer be in its original order after sorting. If you want to keep the original array intact, you can make a copy of it using the slice method:

index.tsx
const numbers = [1, 3, 4, 2, 5];
const sortedNumbers = numbers.slice().sort((a, b) => a - b);
console.log(sortedNumbers); // [1, 2, 3, 4, 5]
console.log(numbers); // [1, 3, 4, 2, 5]
182 chars
5 lines

related categories

gistlibby LogSnag