fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← JavaScript

JavaScript / 6 MIN READ

sort() method

Sort arrays in ascending or descending order

From the original Fervor library. Examples may use older package versions.

The sort() method is used to sort the elements of an array in place, meaning it modifies the original array and returns the sorted array. By default, the sort() method sorts the elements as strings, which may not always produce the expected results when sorting numbers. Therefore, it’s important to understand how to use the sort() method properly to achieve the desired sorting order.

Here’s an example that demonstrates the basic usage of the sort() method:

// Sorting an array of strings
const fruits = ['apple', 'orange', 'banana', 'kiwi'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'kiwi', 'orange']

// Sorting an array of numbers
const numbers = [5, 1, 3, 2, 4];
numbers.sort();
console.log(numbers); // Output: [1, 2, 3, 4, 5]

In the first example, the array fruits is sorted alphabetically because the default comparison is based on strings. In the second example, however, the array numbers is not sorted correctly because the default comparison treats the elements as strings, resulting in an incorrect ordering.

To sort numbers correctly, you need to provide a custom comparison function as an argument to the sort() method. The comparison function takes two parameters, usually referred to as a and b, which represent two elements being compared. The function should return a negative value if a should be sorted before b, a positive value if a should be sorted after b, or 0 if both elements are considered equal.

Here’s an example of sorting an array of numbers using a custom comparison function:

const numbers = [5, 1, 3, 2, 4];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); // Output: [1, 2, 3, 4, 5]

In this case, the comparison function function(a, b) { return a - b; } subtracts b from a. If the result is negative, a is sorted before b, resulting in an ascending order. If the result is positive, b is sorted before a, resulting in a descending order. If the result is 0, the order remains unchanged.

You can also sort an array of objects based on a specific property using a similar approach. For example:

const products = [
  { name: 'Laptop', price: 999 },
  { name: 'Phone', price: 799 },
  { name: 'Tablet', price: 599 }
];

products.sort(function(a, b) {
  return a.price - b.price;
});

console.log(products);
// Output:
// [
//   { name: 'Tablet', price: 599 },
//   { name: 'Phone', price: 799 },
//   { name: 'Laptop', price: 999 }
// ]

In this example, the products array is sorted based on the price property of each object. The comparison function subtracts the price of b from the price of a, resulting in ascending order.

Remember that the sort() method modifies the original array. If you want to keep the original array intact, make a copy before sorting.

That’s a basic overview of how to use the sort() method in JavaScript. You can now apply this knowledge to sort arrays according to your requirements.

Bonus Cool Sort stuff

The sort() method in JavaScript provides a powerful tool for manipulating arrays. Here are some cool things you can do with sort():

  1. Sorting in different orders: By default, sort() arranges elements in ascending order. However, you can easily sort in descending order by modifying the comparison function. Here’s an example:

    const numbers = [5, 1, 3, 2, 4];
    numbers.sort(function(a, b) {
      return b - a; // Sort in descending order
    });
    console.log(numbers); // Output: [5, 4, 3, 2, 1]
    
  2. Sorting an array of objects by a specific property: You can use sort() to arrange an array of objects based on a particular property. Here’s an example:

    const books = [
      { title: 'The Catcher in the Rye', author: 'J.D. Salinger', year: 1951 },
      { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },
      { title: '1984', author: 'George Orwell', year: 1949 }
    ];
    
    // Sort books by year in ascending order
    books.sort(function(a, b) {
      return a.year - b.year;
    });
    
    console.log(books);
    // Output:
    // [
    //   { title: '1984', author: 'George Orwell', year: 1949 },
    //   { title: 'The Catcher in the Rye', author: 'J.D. Salinger', year: 1951 },
    //   { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }
    // ]
    
  3. Sorting based on multiple criteria: You can achieve complex sorting by considering multiple properties or conditions in the comparison function. Here’s an example:

    const students = [
      { name: 'John', age: 20, grade: 'A' },
      { name: 'Jane', age: 19, grade: 'B' },
      { name: 'Alice', age: 20, grade: 'B' },
      { name: 'Bob', age: 19, grade: 'A' }
    ];
    
    // Sort students by age in ascending order,
    // and if ages are equal, sort by grade in descending order
    students.sort(function(a, b) {
      if (a.age === b.age) {
        return b.grade.localeCompare(a.grade);
      }
      return a.age - b.age;
    });
    
    console.log(students);
    // Output:
    // [
    //   { name: 'Bob', age: 19, grade: 'A' },
    //   { name: 'Jane', age: 19, grade: 'B' },
    //   { name: 'Alice', age: 20, grade: 'B' },
    //   { name: 'John', age: 20, grade: 'A' }
    // ]
    
  4. Sorting alphanumeric strings: By default, sort() sorts strings lexicographically, which may not produce the expected results when sorting alphanumeric strings. To sort alphanumeric strings correctly, you can use a comparison function that handles numeric values separately from non-numeric values. Here’s an example:

    const alphanumeric = ['a10', 'a2', 'a20', 'a1'];
    alphanumeric.sort(function(a, b) {
      const numA = parseInt(a.match(/\d+/)[0]);
      const numB = parseInt(b.match(/\d+/)[0]);
    
      if (numA < numB) {
        return -1; // a should be sorted before b
      } else if (numA > numB) {
        return 1; // b should be sorted before a
      } else {
        // If numeric values are equal, sort lexicographically
        return a.localeCompare(b);
      }
    });
    
    console.log(alphanumeric);
    // Output: ['a1', 'a2', 'a10', 'a20']
    

In this example, the alphanumeric array contains strings with a mixture of letters and numbers. The comparison function extracts the numeric values using a regular expression (/\d+/) and converts them to integers using parseInt(). Then, it compares the numeric values and returns the appropriate result. If the numeric values are equal, it falls back to sorting lexicographically using localeCompare().

  1. Sorting with a custom sort order: The sort() method can also be used to sort elements based on a custom sort order. You can provide a custom comparison function that maps elements to a specific order using a predefined mapping or custom logic. Here’s an example:
   const colors = ['blue', 'green', 'red', 'yellow'];

   // Custom sort order based on preference
   const sortOrder = ['red', 'green', 'blue', 'yellow'];

   colors.sort(function(a, b) {
     const indexA = sortOrder.indexOf(a);
     const indexB = sortOrder.indexOf(b);

     return indexA - indexB;
   });

   console.log(colors);
   // Output: ['red', 'green', 'blue', 'yellow']

In this example, the colors array is sorted based on a custom sort order defined by the sortOrder array. The comparison function uses indexOf() to determine the indices of the elements in the sortOrder array and compares them to determine the sorting order.

These are just a few examples of the cool things you can do with the sort() method in JavaScript. The flexibility of the sort() method allows you to implement various sorting strategies and achieve the desired results with ease.

Keep your curiosity going.Explore more JavaScript →
287 TUTORIALS · 22 TOPICSREADY