JavaScript .sort()
The JS .sort() method is used to sort the elements of an array in place. By default, it sorts elements as strings in ascending order. However, a custom comparison function can be provided to achieve more advanced sorting.
JS .sort() Syntax
arr.sort(compareFn)
Parameters:
compareFn(Optional): A function that defines the sort order. It takes two arguments,aandb, and should return:- A negative value if
ashould come beforeb 0ifaandbare considered equal- A positive value if
ashould come afterb
- A negative value if
Return value:
JS .sort() returns the original array with its elements sorted in the given order.
Example 1: Sorting Array of Strings Using JS .sort()
This example uses JS .sort() to sort an array of strings:
const fruits = ['banana', 'apple', 'cherry', 'date'];fruits.sort();console.log(fruits);
Here is the output:
[ 'apple', 'banana', 'cherry', 'date' ]
Example 2: Sorting Array of Numbers Using JS .sort()
This example uses JS .sort() with a comparison function to sort an array of numbers:
const numbers = [10, 5, 20, 1, 100];numbers.sort((a, b) => a - b);console.log(numbers);
Here is the output:
[ 1, 5, 10, 20, 100 ]
Codebyte Example: Sorting Array of Objects Using JS .sort()
This codebyte example uses JS .sort() to sort an array of objects:
Frequently Asked Questions
1. How do I sort numbers in descending order using JS .sort()?
You can reverse the comparison in your function in JS .sort() to sort numbers in descending order:
numbers.sort((a, b) => b - a);
2. Can I use sort() on a string?
No. The sort() method is only available on arrays, not on strings. If you want to sort the characters of a string, you first need to convert it into an array (for example, using split()), apply sort(), and then join it back:
const str = 'hello';const sorted = str.split('').sort().join('');console.log(sorted); // "ehllo"
3. What happens when sort() is used in a list (array)?
When you call sort() on an array, JavaScript converts the elements to strings by default and compares them in Unicode code point order. This means that numbers may not sort as you expect:
const numbers = [10, 1, 5];console.log(numbers.sort()); // [1, 10, 5] (string comparison)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours