get array sorting in javascript

JavaScript provides an in-built method sort() for sorting arrays in ascending order. To sort an array in descending order, we can combine sort() method with another in-built method reverse().

Here's an example of sorting an array of numbers in ascending order using sort():

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

In the above example, sort() method takes a callback function as an argument which compares two consecutive elements of the array and returns a negative, zero, or positive value based on their relationship to each other. If the result is negative, element a comes before element b. If the result is positive, element b comes before element a. If the result is zero, the order of the elements is unchanged.

To sort an array in descending order, we can simply add reverse() method after sort() method as shown below:

index.tsx
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
numbers.sort((a, b) => b - a).reverse();
console.log(numbers); // Output: [9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
153 chars
4 lines

In the above example, sort() method sorts the array in ascending order and reverse() method reverses the order, which makes it a descending order sort.

gistlibby LogSnag