Skip to main content

JavaScript Arrays

JavaScript Array sort

Written by Published

JavaScript sort arranges the elements of an array and changes the original.

By default it sorts as text, which gives surprising results for numbers.

A compare function fixes that.

Example

Example

javascript

const numbers = [10, 1, 5];

console.log(numbers.sort().join(","));

The output is 1,10,5, not 1,5,10.

This is because the values were compared as text.

What is sort?

sort reorders the array in place and also returns it.

With no arguments it converts each element to a string and compares those.

A compare function tells it how to decide the order.

Syntax

Syntax

javascript

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

A negative result puts a first; a positive result puts b first.

Sorting Numbers Properly

Subtracting gives the comparison the numbers it needs.

Example

Example

javascript

const numbers = [10, 1, 5];

console.log(numbers.sort((a, b) => a - b).join(","));

The output is 1,5,10.

Descending Order

Swap the subtraction round.

Example

Example

javascript

const numbers = [10, 1, 5];

console.log(numbers.sort((a, b) => b - a).join(","));

The output is 10,5,1.

Sorting Strings

The default order works for plain lowercase text.

Example

Example

javascript

const names = ["Grace", "Ada", "Alan"];

console.log(names.sort().join(","));

Capital letters sort before lowercase ones, which can surprise you.

Sorting Objects

Compare the property you care about.

Example

Example

javascript

const users = [{ age: 30 }, { age: 22 }];

console.log(users.sort((a, b) => a.age - b.age).map(u => u.age).join(","));

The output is 22,30.

sort Changes the Original

This is the most common trap.

Copy the array first if the original order matters.

Example

Example

javascript

const numbers = [3, 1, 2];
const sorted = [...numbers].sort((a, b) => a - b);

console.log(numbers.join(","));
console.log(sorted.join(","));

The original keeps its order because the copy was sorted.

reverse

reverse flips the order and also changes the original.

Example

Example

javascript

const list = [1, 2, 3];

console.log(list.reverse().join(","));

The output is 3,2,1.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript sort</title>
</head>
<body>

  <h1>JavaScript sort</h1>

  <p id="result"></p>

  <script>
    const scores = [42, 7, 130, 25];
    const sorted = [...scores].sort(function (a, b) {
      return a - b;
    });

    document.getElementById("result").innerHTML =
      "Original: " + scores.join(", ") + "<br>Sorted: " + sorted.join(", ");
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try removing the compare function:

Call sort() with no arguments and see 130 move to the wrong place.

Important Points

  • sort changes the original array.
  • The default order compares values as text.
  • Use (a, b) => a - b to sort numbers.
  • Swap to b - a for descending order.
  • Copy the array first if you need to keep the original order.

Conclusion

sort is powerful but has two traps: text comparison and changing the original.

A compare function solves the first, and a copy solves the second.

Knowing both saves a great deal of confusion.