Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 39 - JavaScript Array Method – sort()

The sort() method is used to sort the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order. However, you can provide a custom sorting function to define different sorting behaviors.


Explanation

  • The method modifies the original array instead of creating a new one.
  • Sorting is based on string Unicode code points unless a compare function is used.
  • If elements are numbers, a compare function is needed to avoid incorrect sorting.

Syntax

array.sort(compareFunction);
  • compareFunction (optional): A function that defines how the elements should be sorted.

Example 1: Sorting Strings Alphabetically

let fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();

console.log(fruits);
// Output: ["Apple", "Banana", "Mango", "Orange"]
  • The default behavior sorts strings in alphabetical order.

Example 2: Sorting Numbers Incorrectly (Default Behavior)

let numbers = [40, 100, 1, 5, 25, 10];

numbers.sort();

console.log(numbers);
// Output: [1, 10, 100, 25, 40, 5]  Incorrect!

*? Since sorting is based on Unicode values, it treats numbers as strings.


Example 3: Sorting Numbers Correctly (Using a Compare Function)

let numbers = [40, 100, 1, 5, 25, 10];

numbers.sort((a, b) => a - b); // Ascending order

console.log(numbers);
// Output: [1, 5, 10, 25, 40, 100]
  • The compare function sorts numbers correctly by comparing values numerically.

Example 4: Sorting in Descending Order

let numbers = [40, 100, 1, 5, 25, 10];

numbers.sort((a, b) => b - a); // Descending order

console.log(numbers);
// Output: [100, 40, 25, 10, 5, 1]
  • This reverses the sorting order.

Example 5: Sorting an Array of Objects

let students = [
    { name: "John", age: 25 },
    { name: "Alice", age: 22 },
    { name: "Bob", age: 30 }
];

students.sort((a, b) => a.age - b.age);

console.log(students);
// Output: [
//   { name: "Alice", age: 22 },
//   { name: "John", age: 25 },
//   { name: "Bob", age: 30 }
// ]
  • Sorting objects based on the age property.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson39-sort.html.
  2. Write the Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Lesson 39 - sort() Method</title>
    </head>
    <body>
       <h2>Sorted Numbers</h2>
       <p id="result"></p>
    
       <script>
           let numbers = [50, 10, 70, 30, 90, 20];
    
           numbers.sort((a, b) => a - b);
    
           document.getElementById("result").textContent = "Sorted: " + numbers.join(", ");
       </script>
    </body>
    </html>
  3. Save the File.

  4. Open it in a Browser to See the Sorted Numbers.


Experiment

  1. Sort an array of words in reverse alphabetical order.
  2. Sort a list of objects based on names (A-Z).
  3. Sort numbers without using a compare function and observe the difference.

Key Takeaways

  • sort() modifies the original array.
  • Default sorting is alphabetical (Unicode-based).
  • Use a compare function to sort numbers correctly.
  • You can sort objects based on properties.