JavaScript Array Sort

JavaScript Tutorial

JavaScript Array Sort — Complete Detailed Guide 

In JavaScript Array Sort is used to arrange array elements. It works for strings, numbers, objects, and dates, but understanding how it works internally is very important.

 Basic Syntax

  • compareFunction → optional

  • If not provided, elements are converted to strings and sorted in lexicographical (dictionary) order

 Default Sorting (Strings)

Example: Alphabetical Order


 

 Works correctly because elements are strings.

 Case Sensitivity Issue


 

 Reason: Capital letters have smaller ASCII/UTF-16 values.

Case-Insensitive Sorting

 Sorting Numbers (MOST IMPORTANT)

Wrong Way (Common Mistake)

 

 Numbers are treated as strings.

Correct Way (Ascending Order)

 

Descending Order

 

 How compareFunction Works

JavaScript checks:

  • Negative valuea comes before b

  • Positive valueb comes before a

  • 0 → order remains unchanged

Return ValueMeaning
< 0a before b
> 0b before a
0no change

 Sorting Arrays of Objects

Example: Sort by Age

 

Sort by Name

 Reverse Sorting


 

reverse() also mutates the original array.

 Sort Without Modifying Original Array

sort() changes the original array.

Solution: Copy first


 

 Sorting Dates


 

 Real-World Use Cases

 Leaderboard Ranking

 E-commerce Price Sorting

 Time Complexity

  • Average: O(n log n)

  • Exact algorithm depends on JavaScript engine (V8, SpiderMonkey, etc.)

 Important Notes

  • sort() is in-place (mutates array)

  • Default sort is string-based

  • Always use a compare function for numbers

  • Modern JS engines use stable sorting

 Quick Cheat Sheet


 

You may also like...