Back to blog

How to use sort in JavaScript - A Complete Guide with Examples

JavaScript's sort method is a powerful tool for sorting arrays. Learn how to sort arrays in JavaScript with practical examples, step-by-step explanations, and real-world use cases.
8 min readLogan FordLogan Ford

What is Array sort in JavaScript?

Array.sort is a powerful array method in JavaScript that allows you to sort the elements of an array in place and returns the sorted array. Whether you're organizing data, creating ordered lists, or preparing data for display, sort is an essential tool in every JavaScript developer's toolkit. It's perfect for when you need to arrange elements in a specific order.


Let's take a look at a simple example:

1const numbers = [5, 3, 8, 1, 2];
2numbers.sort((a, b) => a - b);
3console.log(numbers); // [1, 2, 3, 5, 8]

In this example, we are sorting an array of numbers in ascending order. The sort function takes a comparison function as an argument. The comparison function determines the order of the elements. It takes two arguments: a and b. If the function returns a negative value, a is sorted before b. If it returns a positive value, a is sorted after b. If it returns 0, the order of a and b remains unchanged.


Syntax:

1Array.sort([compareFunction])

The syntax for the sort method is quite simple. Here's a breakdown:

  1. Array: This is the array you want to sort.
  2. sort: This is the method used to sort the array.
  3. compareFunction (optional): This is an optional function that defines the sort order. If omitted, the array elements are converted to strings and sorted according to each character's Unicode code point value.

The compareFunction takes two arguments, a and b, and returns:

  • A negative value if a should come before b.
  • A positive value if a should come after b.
  • 0 if a and b are considered equal.

Here's the syntax again for reference:

1Array.sort([compareFunction])

Use Cases:

The sort function is a powerful tool for organizing data. It's used in modern web applications for:

  • Sorting lists of items
  • Organizing data for display
  • Preparing data for analysis
  • Implementing search and filter functionality

Let's explore some real-world examples that you'll likely encounter in your development journey.


Example 1 - Sorting numbers in ascending order

1// Sorting numbers in ascending order
2const numbers = [5, 3, 8, 1, 2];
3numbers.sort((a, b) => a - b);
4console.log(numbers); // [1, 2, 3, 5, 8]

Let's break down what's happening in this example step by step:

  1. First, we have an array of numbers called numbers.

  2. We use the sort method to sort the numbers in ascending order. Here's how it works:

    • The comparison function (a, b) => a - b is used to compare two numbers.
    • If a is less than b, the function returns a negative value, and a is sorted before b.
    • If a is greater than b, the function returns a positive value, and a is sorted after b.
    • If a is equal to b, the function returns 0, and the order of a and b remains unchanged.

This is a common real-world example of using sort to arrange numbers in ascending order.


Example 2 - Sorting strings alphabetically

1// Sorting strings alphabetically
2const fruits = ['banana', 'apple', 'cherry', 'date'];
3fruits.sort();
4console.log(fruits); // ['apple', 'banana', 'cherry', 'date']

Let's break down this example step by step:


  1. We start with an array of strings called fruits.

  2. We use the sort method to sort the strings alphabetically. By default, the sort method sorts strings in ascending order.


This is a common real-world example of using sort to arrange strings alphabetically.


Example 3 - Sorting objects by a property

1// Sorting objects by a property
2const people = [
3{ name: 'Alice', age: 25 },
4{ name: 'Bob', age: 30 },
5{ name: 'Charlie', age: 20 }
6];
7
8people.sort((a, b) => a.age - b.age);
9console.log(people);

So in this example, we are sorting the people by their age. We are using the age property as the key for sorting.

Let's break down what's happening in this example step by step:


  1. We start with an array of objects called people. Each object represents a person with two properties:
    • name: The name of the person
    • age: The age of the person

  1. We use the sort method to sort the people by their age. Here's how it works:
    • The comparison function (a, b) => a.age - b.age is used to compare the age of two people.
    • If a.age is less than b.age, the function returns a negative value, and a is sorted before b.
    • If a.age is greater than b.age, the function returns a positive value, and a is sorted after b.
    • If a.age is equal to b.age, the function returns 0, and the order of a and b remains unchanged.

This is a common real-world example of using sort to arrange objects by a property.


Practice Questions

It's best to try and solve questions related to the topic you are learning. Below are a set of practice coding challenges to help you understand how to use sort in JavaScript. They are real-world examples of potential problems you might encounter in your day to day work.


JavaScript Array Sort Not Working: How to Correctly Sort Objects by Priority Value
Medium
ArraysSortingHigher order functions+1
React DataGrid: Implementing Column Sorting with useMemo and Hooks
Medium
ReactReact hooksUsememo+1
Optimizing React Product List Performance: Fixing Inefficient Filtering and Sorting Implementation
Hard
ReactReact hooksFiltering+3
Dynamic Product Sorting Implementation
Medium
JavascriptArraysComparator functions+2
Semantic Version Sorting Algorithm
Hard
JavascriptArraysVersion numbers+3

Additional Resources

Common Interview Questions

  1. How would you use sort to implement a custom sorting order?
  2. Can you explain the difference between sort and reverse?
  3. What happens if you don't provide a comparison function to sort?

Keep practicing and experimenting with sort - it's one of the most versatile array methods in JavaScript!

Learn to code, faster

Join 650+ developers who are accelerating their coding skills with TechBlitz.

Share this article