About Lesson
JavaScript Sorting Arrays
JavaScript provides built-in methods for sorting arrays in ascending or descending order. These methods allow you to rearrange the elements of an array based on various criteria.
1. sort()
Sorts the elements of an array in place and returns the sorted array. By default, the sort order is based on string Unicode code points.
Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // Output: ["Apple", "Banana", "Mango", "Orange"]
2. reverse()
Reverses the order of the elements in an array.
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1]
3. Custom Sorting
You can also provide a custom sorting function to the sort()
method to define the sorting criteria.
Example:
const numbers = [10, 5, 20, 25, 15];
numbers.sort((a, b) => a - b); // Sort in ascending order
console.log(numbers); // Output: [5, 10, 15, 20, 25]
These methods provide powerful tools for sorting arrays in JavaScript, allowing you to manipulate the order of elements based on different conditions.