Skip to content
dreamcode
dreamcode
Map
Sorting
Lesson 18 of 48
+15 XP on finish
JS COLLECTIONSChapter 4 · JS Collections Depth

Sorting Arrays

array.sort() sorts in place and, by default, compares items as strings, so [10, 9, 1].sort() gives [1, 10, 9]. Pass a compare function to sort properly: (a, b) => a - b sorts numbers ascending, (a, b) => b - a descending, and a.name.localeCompare(b.name) sorts text alphabetically. Copy first with [...arr] when you need to keep the original order.

Worked example

How it reads

  • Without a compare function, numbers are sorted as text
  • A negative result puts a first, a positive result puts b first
  • Objects sort by whatever the compare function compares
Common mistakes
  • sort() changes the original array. Copy it first if other code still needs the old order.
Cloud tip: Always pass a compare function when sorting numbers. It is one of the most common JavaScript bugs.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Sort the scores from highest to lowest as numbers and print them: [ 100, 42, 18, 7 ].

Press Run to check your work.