JavaScript lesson · 19 min

JavaScript Array sort

Sort text and numbers with compare functions instead of trusting default string sorting.

Code runs locally in your browser

What you will practice

  • Understand default sort behavior.
  • Sort numbers with a compare function.
  • Sort objects by a property.

What this means

`sort` changes the order of items in an array. By default, JavaScript sorts values like strings, which can surprise you with numbers.

A compare function tells sort which item should come first. For numbers, `(a, b) => a - b` sorts ascending.

Because `sort` mutates the array, it is common to copy the array first with spread: `[...items].sort(...)`.

If this is your first time seeing this

Sorting means changing the order of a list.

For numbers and objects, give JavaScript an explicit compare function so it knows what order you mean.

Mini glossary

sort
An array method that orders items.
Compare function
A function that tells sort which item should come first.
Mutation
Changing the original array instead of creating a new one.

Example from everyday life

Sorting is like arranging cards on a table. If you sort alphabetically, `10` can come before `2` because the first character is `1`. If you sort numerically, you compare the actual amounts.

How it works step by step

  1. The code starts with unsorted numbers and tool objects.
  2. `[...scores]` copies the score array so the original is not changed.
  3. `sort((a, b) => a - b)` sorts numbers from smallest to largest.
  4. The tools array is copied and sorted by `uses`, from most used to least used.

Where you will use this

  • A dashboard sorts tools by usage count.
  • A table sorts rows by date, name, price, or status.
  • A search page sorts results by relevance or newest first.

Before you run the code

Always be careful with numeric sorting. The default sort is not numeric.

If preserving the original order matters, copy the array before sorting it.

Common beginner mistakes

  • Using default sort for numbers and getting string-like order.
  • Forgetting that `sort` changes the original array.
  • Sorting objects without choosing which property matters.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingSorts numbers numerically
WaitingSorts objects by usage

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Sort scores descending with `(a, b) => b - a`.
  • Sort tools alphabetically by name.
  • Remove the spread copy and see how the original array changes.