JavaScript Array Sort

JavaScript Array Sort

JavaScript provides several methods to sort arrays — either alphabetically, numerically, or using custom conditions.


 1. sort() – Default Sorting

The sort() method sorts elements alphabetically by default.

Output:

["Apple", "Banana", "Mango"]

⚠ Note: Default sort() converts elements to strings, so numbers may not sort as expected.


 2. Sorting Numbers Correctly

For numbers, use a compare function:


 


 3. reverse() – Reverse Array

Output:

["Charlie", "Bob", "Alice"]

 4. Sorting Array of Objects


 


 5. localeCompare() – Sort Strings with Accents

Output:

["apple", "banana", "éclair"]

Summary Table

Method Action
sort() Default sort (alphabetical)
sort((a,b)=>a-b) Numerical ascending
sort((a,b)=>b-a) Numerical descending
reverse() Reverse array order
localeCompare() Sort strings properly with locale support

Example: Combined Sorting


 

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *