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
afirst, a positive result putsbfirst - 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.


