🎓 A1Learner
🔍

JavaScript Array Sort

The sort method puts the items of an array in order. It changes the array it is called on.

Sort words

The first log shows the starting order. The second log shows the changed array.

const names = ["Pear", "Apple", "Plum"];
console.log(names);
names.sort();
console.log(names);

The text trap

Plain sort reads each number as text. The result follows text order, not value order.

const nums = [10, 9, 80, 100];
nums.sort();
console.log(nums);

Sort by value

The compare function subtracts one number from the other. A negative result puts the first number earlier.

const nums = [10, 9, 80, 100];
nums.sort((a, b) => a - b);
console.log(nums);

Example

const scores = [42, 7, 19, 3];
console.log(scores);
scores.sort((a, b) => a - b);
console.log(scores);
scores.reverse();
console.log(scores);

Key points

  • sort arranges text items in alphabetical order.
  • sort changes the original array.
  • Plain sort reads numbers as text.
  • A compare function tells sort how to order two items.
  • The compare function (a, b) => a - b orders numbers by value.
  • reverse flips the order of the items in an array.

In this example, the compare function sorts the scores from smallest to largest. reverse then flips the sorted array. The last log shows the scores from largest to smallest.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does plain sort() do with the numbers in [10, 9, 80, 100]?