Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How do you sort an array in JavaScript?

JavaScript
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedAug 13, 2024
UpdatedNov 16, 2026
5 min read

Array.prototype.sort() sorts an array in place, but without a comparison function it converts items to strings and sorts them by UTF-16 code units, so [10, 9, 1].sort() gives [1, 10, 9]. Pass a comparator such as (a, b) => a - b for numbers, or use toSorted() (ES2023) to get a new sorted array and leave the original untouched.

Since ES2019 the sort is required to be stable, so items that compare equal keep their original order in every current browser and Node.js version.

Table of Contents

  • Why the default sort surprises people
  • Sorting numbers with a comparator
  • Sorting strings correctly
  • Sorting arrays of objects
  • Mutating versus non-mutating sorts
  • Sorting with a key and caching expensive work
  • Common mistakes
  • Frequently Asked Questions
    • Is JavaScript sort stable?
    • What algorithm does sort use?
    • How do I sort in descending order?
    • How do I sort an array of dates?
  • Summary

Why the default sort surprises people

javascript
javascript
Loading syntax highlighting...
text

The default comparison turns every element into a string, so "10" comes before "9". Two further rules apply: undefined values are always moved to the end, and holes in sparse arrays are left at the end as well.

Sorting numbers with a comparator

A comparator receives two items and returns a negative number, zero or a positive number:

javascript
javascript
Loading syntax highlighting...

Subtraction is fine for finite numbers, but it returns NaN with NaN, Infinity - Infinity and mixed values. For data you do not control, write the comparison explicitly: (a, b) => (a < b ? -1 : a > b ? 1 : 0). For BigInt values, subtraction cannot be returned directly because the result must be a number, so compare with < and >.

Sorting strings correctly

javascript
javascript
Loading syntax highlighting...
text

localeCompare respects language rules, accents and case. For large arrays, create one Intl.Collator and reuse it because it is much faster than calling localeCompare repeatedly:

javascript
javascript
Loading syntax highlighting...
text

numeric: true sorts digit sequences by value, which gives natural order for file names.

Sorting arrays of objects

javascript
javascript
Loading syntax highlighting...

The || falls through to the second key only when the first comparison returns 0. The result is oldest first, with ties ordered by name. Dates can be sorted by subtraction too, because Date objects convert to timestamps: events.sort((a, b) => a.date - b.date).

Mutating versus non-mutating sorts

sort() changes the array it is called on and also returns that same array. This breaks React state and other immutable code. ES2023 added non-mutating methods:

MutatingNon-mutating (ES2023)
arr.sort(cmp)arr.toSorted(cmp)
arr.reverse()arr.toReversed()
arr.splice(...)arr.toSpliced(...)
javascript
javascript
Loading syntax highlighting...
text

toSorted is available in current evergreen browsers and Node.js 20 and later. For older environments, copy first with [...original].sort(cmp). Typed arrays have their own sort and toSorted, and a typed array sorts numerically by default.

Sorting with a key and caching expensive work

When computing the sort key is expensive, calculate it once per item instead of inside the comparator, which runs many times per element. This is the decorate, sort, undecorate pattern:

javascript
javascript
Loading syntax highlighting...

expensiveKey stands for any costly function, such as parsing a date from a string or reading a property through several layers. The comparator now does only a cheap numeric comparison. For small arrays the difference is negligible, so apply this only when profiling shows the comparator is a hot spot.

Common mistakes

  • Returning a boolean such as (a, b) => a > b. A comparator must return a number; booleans become 1 or 0 and never -1, giving inconsistent results.
  • Forgetting that sort() mutates shared arrays.
  • Sorting mixed types with the default comparator.
  • Using localeCompare on null or undefined values; filter or default them first.

Frequently Asked Questions

Is JavaScript sort stable?

Yes. The specification has required a stable sort since ES2019, so equal items keep their relative order.

What algorithm does sort use?

The specification does not mandate one. V8 uses TimSort, and the complexity is typically O(n log n).

How do I sort in descending order?

Swap the operands in the comparator (b - a), or sort ascending and call reverse() (or toReversed()).

How do I sort an array of dates?

Subtract them (a.date - b.date) or compare getTime() values. ISO 8601 strings also sort correctly as plain strings.

Summary

Always give sort() a comparator unless you want string order. Use a - b for numbers, localeCompare or Intl.Collator for text, chain keys with ||, and prefer toSorted() when you must not mutate the original array.

Share