Skip to main content

sort() Method – How to Sort Array Elements in JavaScript

Whenever you use sort() on an array, the method does the following:

  1. It sorts its calling array's items in ascending (or descending) order.
  2. It returns the calling array in its sorted state.

Example of the sort() Method

const fruitsArray = ["banana", "coconut", "dates", "apple"];

fruitsArray.sort();

// The invocation above will return:
// ["apple", "banana", "coconut", "dates"]

Try it on StackBlitz

The above snippet used sort() to sort the fruitsArray in ascending order.

note
  • sort() is a destructive method that alters the original array. (We will discuss how you can use sort() non-destructively later in this article).
  • A calling array is an array on which you used sort(). So, in fruitsArray.sort(), fruitsArray is the calling array.
  • You can also sort elements in descending order. We will discuss how later in this article.
  • sort() is sometimes written as Array.prototype.sort() because it is a method of the Array object's prototype property.

Syntax of the sort() Method

Here is sort()'s syntax:

callingArray.sort();

sort() also accepts an optional argument. Here is the syntax:

callingArray.sort(compareFunction);

function compareFunction(a, b) {
/* ... */
}

The inline alternative of the above syntax is this:

callingArray.sort(function compareFunction(a, b) {
/* ... */
});

The arrow function alternative of the above syntax is as follows:

callingArray.sort((a, b) => {
/* ... */
});

The compareFunction argument is a comparison function for comparing array elements. We will discuss it in-depth later in this article. For now, though, let's talk about how sort() works without an argument.

How sort() Works without an Argument

Whenever you use sort() without the optional callback argument, the method will do the following:

  1. It converts the calling array's elements to strings.
  2. It will automatically sort the array items in ascending order, according to each element's Unicode point value.

Therefore, you may get unexpected outputs if the array's elements are numbers.

For instance, 3 comes before 100 in the numeral ordering system. But since sort() converts numbers to strings, "100" comes before "3" in the Unicode ordering system.

Example 1: How to use sort() without an argument on an array of alphabets

const stringArray = ["F", "A", "B", "D", "E", "C"];

stringArray.sort();

// The invocation above will return:
// ["A", "B", "C", "D", "E", "F"]

Try it on StackBlitz

sort() sorted the stringArray in ascending order according to the items' Unicode point values.

Example 2: How to use sort() without an argument on an array of numeric strings

const stringArray = ["40", "100", "6", "22", "59", "3300"];

stringArray.sort();

// The invocation above will return:
// ["100", "22", "3300", "40", "59", "6"]

Try it on StackBlitz

sort() sorted the stringArray in ascending order according to their Unicode point values.

note

The sort() method listed "6" last because its Unicode value is greater than all other items in the stringArray.

Example 3: How to use sort() without an argument on an array of numbers

const numbersArray = [40, 100, 6, 22, 59, 3300];

numbersArray.sort();

// The invocation above will return:
// [100, 22, 3300, 40, 59, 6]

Try it on StackBlitz

sort() sorted the numbersArray in ascending order according to their Unicode point values.

note
  • The sort() method first converted the numbers to strings.
  • sort() listed 6 last because "6" comes after the five other elements in the Unicode ordering system.

By default, sort() sorts its calling array's elements in ascending order, according to their Unicode point values. But you can use the comparison function argument to specify the sorting order. Let's talk more about this now.

How to Specify sort()'s Sorting Order with the compareFunction Argument

The compareFunction argument allows you to define the exact way you want the computer to sort a list of elements.

In other words, whenever you pass a compareFunction argument to the sort() method, sort() will arrange its calling array's items based on the function's return values.

note

The sort() method does not care how the compareFunction returns its value. All it requires is a positive number, negative digit, or zero to understand the sorting order you need.

Syntax of the compareFunction Argument

The compareFunction() accepts two optional parameters. Here is the syntax:

function compareFunction(a, b) {
/* ... */
}
  • Parameters a and b represent the two array items sort() is currently comparing.
  • Parameter a represents the first of the two array items sort() is currently comparing.
  • Parameter b represents the second of the two array items sort() is currently comparing.

How sort()'s compareFunction Argument Works

Suppose sort() is sorting two items using the comparefunction argument. In that case, here's what will happen:

  1. sort() sends the two items to the compareFunction.
  2. If the function accepts parameters, it will receive the two items as its parameters a and b, respectively.
  3. Suppose the function returns an a − b statement. In that case, the computer will subtract the Unicode point value of element b from a.
  4. If the function returns a positive value, the computer will position element a after b.
  5. If the function returns a negative value, the computer will place element a before b.
  6. Suppose the subtraction returned zero (0). In that case, element a and element b's positioning will remain unchanged.

Example 1: How to sort an array of two elements in ascending order

const numbersArray = [10, 7];

numbersArray.sort((a, b) => {
return a – b;
});

console.log(numbersArray);

// The invocation above will return: [7, 10]

Try it on StackBlitz

The snippet above positioned 10 after 7 because the compareFunction returned a positive number (3).

CodeSweetly ads

Design in Figma, launch in Webflow

Bring your static designs to life with IX2, wire up content using our powerful CMS, and one-click publish onto the fastest hosting infrastructure.
Find out more

Example 2: How to sort an array of two elements in descending order

const numbersArray = [10, 7];

numbersArray.sort((a, b) => {
return b - a;
});

console.log(numbersArray);

// The invocation above will return: [10, 7]

Try it on StackBlitz

The above snippet positioned 10 before 7 because the compareFunction returned a negative number (-3).

Example 3: How to sort an array of five elements in ascending order

const numbersArray = [3, 1, 4, -4, 0, 2, 5];

numbersArray.sort((a, b) => {
return a - b;
});

console.log(numbersArray);

// The invocation above will return:
// [-4, 0, 1, 2, 3, 4, 5]

Try it on StackBlitz

The snippet above sorted the numbersArray based on the compareFunction's return value each time it compares parameters a and b.

In other words, the logic sort() used to sort the numbersArray has the following form:

const numbersArray = [3, 1, 4, -4, 0, 2, 5];

numbersArray.sort((a, b) => {
return a - b;
});

/* The numbersArray sorting logic:
3 – (1) = positive => sort() places 3 after 1,
3 – (4) = negative => sort() places 3 before 4,
3 – (–4) = positive => sort() places 3 after –4,
3 – (0) = positive => sort() places 3 after 0,
3 – (2) = positive => sort() places 3 after 2,
3 – (5) = negative => sort() places 3 before 5,
*/

How to Use sort() without Changing the Original Array

The sort() method is destructive by default. In other words, its default setting is to change the original array. But you can use it in a non-destructive way by creating a shallow copy of the original array before invoking sort().

tip

Read how spread works on objects containing non-primitives to understand the deep and shallow copy concept.

Example 1: How to make sort() non-destructive with the spread operator

Here's how you to use the spread operator to make sort() non-destructive:

  1. Use the spread operator (...) to duplicate the original array into a new one.
  2. Use sort() on the new array.

Here's an example:

// Define an array:
const numbersArray = [77, 1000, 9, 300, 23];

// Duplicate the numbersArray into a new array:
const newNumbersArray = [...numbersArray];

// Sort the newNumbersArray in ascending order:
const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => {
return a - b;
});

// Log the sortedVersionOfNewNumbersArray to the console:
console.log(sortedVersionOfNewNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the newNumbersArray to the console:
console.log(newNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the numbersArray to the console:
console.log(numbersArray);

// The invocation above will return:
// [77, 1000, 9, 300, 23]

Try it on StackBlitz

You can see that numbersArray remained the same while sort() altered the newNumbersArray.

The numbersArray remained unchanged because we did not use sort() on it. Instead, we invoked sort() on the newNumbersArray.

Example 2: How to make sort() non-destructive with the Array.from() method

Here's how you to use Array.from() to make sort() non-destructive:

  1. Use Array.from() to duplicate the original array.
  2. Use sort() on the new array.

Here's an example:

// Define an array:
const numbersArray = [77, 1000, 9, 300, 23];

// Duplicate the numbersArray:
const newNumbersArray = Array.from(numbersArray);

// Sort the newNumbersArray in ascending order:
const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => {
return a - b;
});

// Log the sortedVersionOfNewNumbersArray to the console:
console.log(sortedVersionOfNewNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the newNumbersArray to the console:
console.log(newNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the numbersArray to the console:
console.log(numbersArray);

// The invocation above will return:
// [77, 1000, 9, 300, 23]

Try it on StackBlitz

You can see that numbersArray remained the same while sort() altered the newNumbersArray.

The numbersArray remained unchanged because we did not use sort() on it. Instead, we invoked sort() on the newNumbersArray.

Example 3: How to make sort() non-destructive with the concat() method

Here's how you to use concat() to make sort() non-destructive:

  1. Use concat() to duplicate the original array into a new one.
  2. Use sort() on the new array.

Here's an example:

// Define an array:
const numbersArray = [77, 1000, 9, 300, 23];

// Duplicate the numbersArray into a new array:
const newNumbersArray = [].concat(numbersArray);

// Sort the newNumbersArray in ascending order:
const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => {
return a - b;
});

// Log the sortedVersionOfNewNumbersArray to the console:
console.log(sortedVersionOfNewNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the newNumbersArray to the console:
console.log(newNumbersArray);

// The invocation above will return:
// [9, 23, 77, 300, 1000]

// Log the numbersArray to the console:
console.log(numbersArray);

// The invocation above will return:
// [77, 1000, 9, 300, 23]

Try it on StackBlitz

You can see that numbersArray remained the same while sort() altered the newNumbersArray.

The numbersArray remained unchanged because we did not use sort() on it. Instead, we invoked sort() on the newNumbersArray.

How to Use sort() to Shuffle an Array

Here's how to use sort() to shuffle (reorder) the items of an array:

  1. Use the compareFunction argument to return a positive number, negative digit, or zero at random.
  2. Use sort() to sort the array based on the compareFunction's return value.

Here's an example:

// Define an array:
const numbersArray = [1, 2, 3, 4, 5, 6, 7];

// Shuffle the numbersArray:
numbersArray.sort(function compareFunction() {
return Math.random() - 0.5;
});

Here's what we did in the snippet above:

  1. We defined an array of seven numbers.
  2. We used Math.random() − 0.5 to return a random number between −0.5 and 0.5.
  3. The sort() method sorts the numbersArray based on the compareFunction's return values. For instance, while sorting 1 and 2, suppose the compareFunction returned 0.3606023192109793 (a positive number). In that case, the computer will place 1 after 2.

Therefore, each time you invoke numbersArray.sort(), the computer will return a shuffled array similar to this:

/* 
[ 4, 2, 6, 1, 3, 5, 7 ]
[ 4, 1, 3, 2, 6, 7, 5 ]
[ 1, 4, 3, 6, 5, 2, 7 ]
[ 7, 4, 6, 3, 1, 2, 5 ]
*/

Try it on StackBlitz

Note the following:

  • We omitted the compareFunction's parameters because the function gets its return values from the Math.random() − 0.5 statement, not from subtracting parameters a and b.
  • Using the parameters a and b syntax to get compareFunction's output creates a consistent sorting order because the function returns its values by analyzing elements from the calling array.
  • The Math.random() − 0.5 syntax generates a mishmash arrangement because the function returns its values based on random analyses.
  • The Math.random() − 0.5 code will return a value between −0.5 and 0.5 because Math.random() always returns a random numeral between 0 (inclusive) and 1 (exclusive).
tip

The Fisher-Yates shuffle algorithm is a better option for shuffling an array because it is sequential.

Important Stuff to Know about the sort() Method

The sort() method moves all empty slots and undefined items to the end of the array.

Here's an example:

const mixedArray = ["F", , "A", undefined, "B", undefined, "D", "E", , "C"];

mixedArray.sort();

// The invocation above will return:
// ["A", "B", "C", "D", "E", "F", undefined, undefined, <2 empty slots>]

Try it on CodePen

Overview

This article discussed what the JavaScript sort() method does. We also used examples to see how it works.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article