JAVASCRIPT Tutorial

Sorting in JS

What is Sorting?

Sorting is the process of arranging elements of an array in a specific order (e.g., ascending or descending).

JavaScript's Sort() Method

The sort() method is used to sort arrays in JavaScript. By default, it sorts elements in ascending order.

How to Use Sort()

  1. Call the sort() method on an array.
    const arr = [5, 2, 8, 1];
    arr.sort();
    
  2. Optionally, provide a comparison function. The comparison function takes two arguments and returns a number:
    • 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
    
  3. The sort() method modifies the original array. The sorted array is not returned. To keep the original array intact, create a copy before sorting.
    const copy = [...arr]; // Create a copy
    copy.sort(); // Sort the copy
    

Example: Sorting an Array in Ascending Order

const arr = [5, 2, 8, 1];
arr.sort();

console.log(arr); // [1, 2, 5, 8]