Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to sort an array in JavaScript

Sorting is a common operation in programming that involves arranging data in a particular order. In this tutorial, we will learn how to sort an array in JavaScript. We will discuss some of the built-in JavaScript methods for sorting arrays and also dive into writing our custom sorting functions.

Imagine you have a collection of books, and you want to arrange them in alphabetical order. Sorting algorithms work in a similar way by comparing and organizing data in a specific order, such as ascending or descending.

JavaScript's Built-in Sorting Method: Array.sort()

JavaScript provides a built-in method called sort() that can be used to sort the elements of an array. The sort() method sorts the elements of an array in place, meaning that it modifies the original array instead of creating a new, sorted array.

Let's start with the basics. Here's an example of how to use the sort() method:

let numbers = [34, 1, 67, 3, 99, 5];
numbers.sort();
console.log(numbers);
// Output: [1, 3, 34, 5, 67, 99]

In this example, the sort() method is called on an array of numbers. The numbers are then sorted in ascending order, and the sorted array is displayed in the console.

However, there's a catch. The sort() method by default sorts the elements as strings. This means that it will not give the expected result when sorting numbers. Let's see an example:

let numbers = [10, 2, 20, 1];
numbers.sort();
console.log(numbers);
// Output: [1, 10, 2, 20]

In this example, the sort() method sorts the numbers as strings, which results in an incorrect order. To fix this, we need to provide a comparison function to the sort() method.

Using a Comparison Function

A comparison function is a function that takes two arguments, typically referred to as a and b, and returns a value based on the comparison of the two arguments. The comparison function should return:

  • A negative, zero, or positive value if a should be sorted before, equal to, or after b, respectively.

Here's an example of using a comparison function to sort an array of numbers in ascending order:

let numbers = [10, 2, 20, 1];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);
// Output: [1, 2, 10, 20]

In this example, the comparison function returns the difference between a and b. When the difference is negative, it means that a should be sorted before b. When the difference is positive, it means that a should be sorted after b. If the difference is zero, it means that a and b are equal, and their order doesn't matter.

We can also use an arrow function to make the code more concise:

let numbers = [10, 2, 20, 1];
numbers.sort((a, b) => a - b);
console.log(numbers);
// Output: [1, 2, 10, 20]

Sorting in Descending Order

To sort the array in descending order, simply reverse the order of subtraction in the comparison function:

let numbers = [10, 2, 20, 1];
numbers.sort((a, b) => b - a);
console.log(numbers);
// Output: [20, 10, 2, 1]

Sorting an Array of Strings

The sort() method works well with arrays of strings without the need for a comparison function. Let's see an example:

let fruits = ['apple', 'banana', 'kiwi', 'mango'];
fruits.sort();
console.log(fruits);
// Output: ['apple', 'banana', 'kiwi', 'mango']

If you want to sort an array of strings in descending order, you can use the reverse() method after sorting the array:

let fruits = ['apple', 'banana', 'kiwi', 'mango'];
fruits.sort().reverse();
console.log(fruits);
// Output: ['mango', 'kiwi', 'banana', 'apple']

Sorting an Array of Objects

Sorting an array of objects requires a custom comparison function that compares the object properties. Let's say we have an array of objects representing students and their grades:

let students = [
  { name: 'Alice', grade: 90 },
  { name: 'Bob', grade: 82 },
  { name: 'Charlie', grade: 88 },
  { name: 'David', grade: 95 }
];

To sort the students array by their grades, we can use the sort() method with a custom comparison function:

students.sort((a, b) => a.grade - b.grade);
console.log(students);
// Output:
// [
//   { name: 'Bob', grade: 82 },
//   { name: 'Charlie', grade: 88 },
//   { name: 'Alice', grade: 90 },
//   { name: 'David', grade: 95 }
// ]

In this example, the custom comparison function compares the grade property of the student objects, resulting in a sorted array based on the student's grades.

Conclusion

In this tutorial, we've covered how to sort arrays in JavaScript using the built-in sort() method and custom comparison functions. We've also discussed sorting arrays of numbers, strings, and objects. By understanding these techniques, you can easily organize and manipulate data in your JavaScript applications.