Sort() Method in JavaScript.

Sort() Method in JavaScript.

Sorting is a fundamental operation in programming. In JavaScript, sorting can be performed on arrays using built-in methods and custom logic. This guide covers the essentials and advanced techniques for sorting in JavaScript, with detailed examples and step-by-step explanations.


1. Sorting Basics with sort()

The sort() method sorts the elements of an array in place and returns the sorted array. By default, sort() converts elements to strings and compares their UTF-16 code unit values.

Example: Sorting Strings

const fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Cherry"]

Explanation:

  1. The sort() method is called on the fruits array.

  2. Each element in the array is converted to a string if it isn't already.

  3. The strings are compared based on their UTF-16 code unit values.

  4. The array is modified in place, so the original array is now sorted alphabetically.


2. Numeric Sorting

Since sort() converts elements to strings by default, sorting numbers requires a comparison function.

Example: Sorting Numbers

const numbers = [10, 2, 5, 1];

// Ascending order
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 10]

// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // [10, 5, 2, 1]

Step-by-Step (Ascending Order):

  1. The sort() method is called with a comparison function (a, b) => a - b.

  2. The comparison function subtracts b from a:

    • If the result is negative, a comes before b.

    • If the result is zero, their order is unchanged.

    • If the result is positive, b comes before a.

  3. The array is sorted in ascending order.

Step-by-Step (Descending Order):

  1. The comparison function is changed to (a, b) => b - a.

  2. This reverses the logic, so larger numbers are placed before smaller ones.


3. Custom Sorting with compareFunction

The compareFunction allows custom sorting logic by comparing two elements a and b.

Example: Sorting Strings by Length

const words = ["apple", "kiwi", "banana", "cherry"];
words.sort((a, b) => a.length - b.length);
console.log(words); // ["kiwi", "apple", "banana", "cherry"]

Explanation:

  1. The compareFunction calculates the difference in length between two strings.

    • For example, "apple".length - "kiwi".length evaluates to 5 - 4 = 1.
  2. Positive results place b before a.

  3. Negative results place a before b.

  4. The array is sorted by the length of each string.


4. Sorting Objects

Objects can be sorted by their properties using a custom compareFunction.

Example: Sorting by Age

const people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 }
];
people.sort((a, b) => a.age - b.age);
console.log(people);

Explanation:

  1. The compareFunction accesses the age property of each object.

  2. It subtracts b.age from a.age:

    • For example, { name: "Alice", age: 25 } and { name: "Charlie", age: 20 } will evaluate as 25 - 20 = 5.
  3. The array is sorted in ascending order based on the age property.

  4. The result is:

     [
       { name: "Charlie", age: 20 },
       { name: "Alice", age: 25 },
       { name: "Bob", age: 30 }
     ]
    

5. Stable Sorting

JavaScript's sort() method is stable (since ECMAScript 2019). Stable sorting maintains the relative order of elements that are equal.

Example:

const items = [
  { name: "item1", value: 10 },
  { name: "item2", value: 20 },
  { name: "item3", value: 10 }
];
items.sort((a, b) => a.value - b.value);
console.log(items);

Explanation:

  1. The compareFunction compares the value property.

  2. Items with the same value retain their original order.

  3. Result:

     [
       { name: "item1", value: 10 },
       { name: "item3", value: 10 },
       { name: "item2", value: 20 }
     ]
    

6. Using localeCompare() for Internationalization

The localeCompare() method is useful for sorting strings in a locale-aware manner.

Example:

const names = ["Émile", "Emma", "Eve"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // ["Emma", "Eve", "Émile"]

Explanation:

  1. localeCompare() compares strings based on the current locale settings.

  2. This ensures proper sorting of special characters and accents.


7. Case-Insensitive Sorting

To sort strings case-insensitively, use toLowerCase() in the compareFunction.

Example:

const cities = ["paris", "London", "new york", "Amsterdam"];
cities.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(cities); // ["Amsterdam", "London", "new york", "paris"]

Explanation:

  1. The toLowerCase() method converts each string to lowercase.

  2. The localeCompare() method compares the strings in a locale-aware manner.


8. Performance Considerations

  • Sorting is O(n log n) on average.

  • Sorting large arrays can impact performance, so optimizing the compareFunction to avoid unnecessary computations.

Example:

const largeArray = Array.from({ length: 100000 }, () => Math.random());
largeArray.sort((a, b) => a - b);

Explanation:

  1. A large array of random numbers is created using Array.from().

  2. The sort() method efficiently sorts the array in ascending order.


    Hope that helps.