Home / Companies / LogRocket / Blog / Post Details
Content Deep Dive

JavaScript’s sort() method: From basics to custom sorting

Blog post from LogRocket

Post Details
Company
Date Published
Author
Joseph Mawa
Word Count
3,337
Company Posts That Month
82
Language
-
Hacker News Points
-
Post removed?
No
Summary

JavaScript offers two primary methods for sorting arrays: `Array.prototype.sort` and `Array.prototype.toSorted`. Both methods allow customizable sorting through a compare function, which determines the order of elements based on their values. By default, without a compare function, both methods convert elements to strings and sort them according to their UTF-16 code units, which can lead to unexpected results, such as "123" being sorted before "20" due to character code comparisons. The `sort` method mutates the original array, while `toSorted` returns a new array, preserving the original. For language-sensitive string sorting, JavaScript provides the `Intl.Collator` object and the `String.prototype.localeCompare` method, which accommodate different languages' sorting rules. These methods are not limited to arrays and can be applied to array-like objects with a length property. The choice between `sort` and `toSorted` depends on whether the original array should be altered or not.

Trends Found in this Post

No tracked trend matches for this post yet.

Use This Data

Use this post, company, and trend context to find content marketing opportunities, perform competitive analysis, or address product feature gaps via the Plushcap MCP server or the Plushcap API.