JAVASCRIPT Tutorial
Sorting is the process of arranging elements of an array in a specific order (e.g., ascending or descending).
The sort() method is used to sort arrays in JavaScript. By default, it sorts elements in ascending order.
const arr = [5, 2, 8, 1];
arr.sort();
a and b are the elements being compared.a < b: Return a negative number to sort a before b.a > b: Return a positive number to sort b before a.a === b: Return 0 to leave the order unchanged.arr.sort((a, b) => a - b); // Sort in ascending order
arr.sort((a, b) => b - a); // Sort in descending order
const copy = [...arr]; // Create a copy
copy.sort(); // Sort the copy
const arr = [5, 2, 8, 1];
arr.sort();
console.log(arr); // [1, 2, 5, 8]