How to Sort Array in JavaScript: Simple Guide
Use the
array.sort() method to sort arrays in JavaScript. By default, it sorts elements as strings in ascending order, but you can provide a compareFunction to customize sorting for numbers or other criteria.Syntax
The basic syntax of the sort() method is:
array.sort(): Sorts elements as strings in ascending order.array.sort(compareFunction): Sorts elements using a function that defines the sort order.
The compareFunction takes two arguments and returns a number:
- Negative if first argument should come before second.
- Zero if they are equal.
- Positive if first argument should come after second.
javascript
array.sort([compareFunction])
Example
This example shows sorting an array of numbers in ascending and descending order using sort() with a compare function.
javascript
const numbers = [40, 100, 1, 5, 25, 10]; // Sort ascending numbers.sort((a, b) => a - b); console.log('Ascending:', numbers); // Sort descending numbers.sort((a, b) => b - a); console.log('Descending:', numbers);
Output
Ascending: [1, 5, 10, 25, 40, 100]
Descending: [100, 40, 25, 10, 5, 1]
Common Pitfalls
By default, sort() converts elements to strings and sorts them lexicographically, which can cause unexpected results with numbers.
For example, sorting numbers without a compare function sorts them as strings:
javascript
const nums = [10, 2, 30]; nums.sort(); console.log(nums); // Output: [10, 2, 30] (unexpected order) // Correct way with compare function nums.sort((a, b) => a - b); console.log(nums); // Output: [2, 10, 30]
Output
[10, 2, 30]
[2, 10, 30]
Quick Reference
| Method | Description | Example |
|---|---|---|
| array.sort() | Sorts elements as strings in ascending order | ["apple", "banana", "cherry"].sort() |
| array.sort((a,b) => a - b) | Sort numbers ascending | [3,1,2].sort((a,b) => a - b) |
| array.sort((a,b) => b - a) | Sort numbers descending | [3,1,2].sort((a,b) => b - a) |
Key Takeaways
Use array.sort() to sort arrays, but remember it sorts elements as strings by default.
Provide a compare function like (a, b) => a - b to sort numbers correctly in ascending order.
Without a compare function, numbers may sort incorrectly because they are treated as strings.
The compare function should return negative, zero, or positive to define order.
Sorting strings works well with default sort(), but custom logic is needed for complex sorting.