Sorting Arrays

  • This lesson explains how to sort arrays in JavaScript.
  • Introduction to Sorting Arrays

    In real-world programming, data is rarely used in random order.
    We often need data to be arranged in a meaningful way, such as:

    • Names in alphabetical order

    • Marks from highest to lowest

    • Prices from low to high

    • Latest items first

    Sorting arrays helps us organize data so that it is:

    • Easy to read

    • Easy to search

    • Easy to analyze

    JavaScript provides built-in methods to sort and reverse arrays efficiently.

    Topics Covered in This Lesson

    1. Sorting Arrays

    2. Reversing Arrays

    Sorting Arrays

    What is Sorting ?

    Sorting means arranging elements of an array in a specific order, such as:

    • Ascending order (A → Z, 1 → 9)

    • Descending order (Z → A, 9 → 1)

      JavaScript sort() Method

      JavaScript provides the sort() method to sort array elements.

      Syntax

      array.sort();

      • Sorts the array in place

      • Modifies the original array

      • By default, sorts elements as strings

    sort Method for Strings

    Arranges array elements in alphabetical order by default.

    // Sorting string array
    
    let fruits = ["Banana", "Apple", "Mango", "Orange"];
    
    fruits.sort();
    
    console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
    • Explanation

      • Strings are sorted alphabetically

      • Works perfectly for string arrays

      Important About sort()

      The sort() method converts elements to strings and compares them by Unicode values.

      This causes unexpected results for numbers.

    Sorting Numbers Incorrectly

    Default sort treats numbers as strings, leading to unexpected order.

    // Incorrect number sorting
    
    let numbers = [10, 5, 20, 2];
    
    numbers.sort();
    
    console.log(numbers); // [10, 2, 20, 5]
    • Why This Happens

      • Numbers are treated as strings

      • "10" comes before "2"

        Correct Way to Sort Numbers (Ascending Order)

        To sort numbers correctly, we use a compare function.

        Syntax with Compare Function

        array.sort(function(a, b) {

          return a - b;

        });

      Numeric Ascending Sort

      Sorts numbers correctly in increasing order using a compare function.

      // Ascending sort
      
      let numbers = [10, 5, 20, 2];
      
      numbers.sort(function(a, b) {
        return a - b;
      });
      
      console.log(numbers); // [2, 5, 10, 20]
      • How the Compare Function Works

        • If result is negative → a comes before b

        • If result is positive → b comes before a

        • If result is zero → order remains unchanged

      Numeric Descending Sort

      Arranges numbers from highest to lowest using a compare function.

      // Descending sort
      
      let numbers = [10, 5, 20, 2];
      
      numbers.sort(function(a, b) {
        return b - a;
      });
      
      console.log(numbers); // [20, 10, 5, 2]
      • Sorting Using Arrow Function (Modern JavaScript)

      Sorting with Arrow Function

      Uses arrow function syntax for cleaner and shorter sorting logic.

      // Sorting using arrow function
      
      let numbers = [10, 5, 20, 2];
      
      numbers.sort((a, b) => a - b);
      
      console.log(numbers); // [2, 5, 10, 20]
      • Sorting an Array of Strings (Case Sensitivity)

      String Sorting Case Sensitivity

      Default sorting is case-sensitive and follows Unicode order.

      // Case-sensitive string sorting
      
      let names = ["rahul", "Amit", "neha", "Vikas"];
      
      names.sort();
      
      console.log(names); // ["Amit", "Vikas", "neha", "rahul"]
      • Uppercase letters are sorted before lowercase letters.

        Sorting Objects Inside an Array

        Real-world arrays often contain objects.

      Sorting Objects by Property

      Orders objects in an array based on a specific key value.

      // Sorting objects by marks
      
      let students = [
        { name: "Amit", marks: 85 },
        { name: "Neha", marks: 92 },
        { name: "Rahul", marks: 78 }
      ];
      
      students.sort((a, b) => a.marks - b.marks);
      
      console.log(students);
      // [
      //   { name: "Rahul", marks: 78 },
      //   { name: "Amit", marks: 85 },
      //   { name: "Neha", marks: 92 }
      // ]
      • Reversing Arrays

        What is Reversing ?

        Reversing means changing the order of elements so that:

        • First element becomes last

        • Last element becomes first

        JavaScript reverse() Method

        Syntax

        array.reverse();

        • Reverses the array in place

        • Modifies the original array

      reverse Method in Arrays

      Changes the order of elements by reversing the array in place.

      // Reverse an array
      
      let numbers = [1, 2, 3, 4, 5];
      
      numbers.reverse();
      
      console.log(numbers); // [5, 4, 3, 2, 1]
      • Sorting + Reversing Together

        We can combine sort() and reverse().

      Descending Order using sort and reverse

      First sorts numbers in ascending order, then reverses for descending output.

      // Descending order using sort + reverse
      
      let numbers = [10, 5, 20, 2];
      
      numbers.sort((a, b) => a - b).reverse();
      
      console.log(numbers); // [20, 10, 5, 2]
      • Important Points to Remember

        • sort() modifies the original array

        • reverse() also modifies the original array

        • Use slice() if you want to keep original data safe

      Preserving Original Array While Sorting

      Uses slice to avoid modifying the original array during sorting.

      // Preserve original array
      
      let numbers = [10, 5, 20, 2];
      
      let sortedNumbers = numbers.slice().sort((a, b) => a - b);
      
      console.log(numbers);        // original unchanged
      console.log(sortedNumbers);  // sorted array
      • Common Mistakes

        • Forgetting that sort() treats numbers as strings

        • Not using compare function for numeric sorting

        • Modifying original array unintentionally

        • Confusing sorting with reversing

        Best Practices for Sorting Arrays

        • Always use compare function for numbers

        • Use arrow functions for clean code

        • Avoid mutating original array if not required

        • Comment complex sorting logic

        • Test sorting with multiple values