How to Sort Array of Strings in JavaScript Easily
To sort an array of strings in JavaScript, use the
array.sort() method. This method sorts the strings in place in ascending order by default, based on Unicode code points.Syntax
The basic syntax to sort an array of strings is:
array.sort([compareFunction])Here:
arrayis your array of strings.sort()changes the array order.compareFunctionis optional and lets you customize sorting rules.
javascript
array.sort()
Example
This example shows how to sort an array of strings alphabetically using sort(). It also shows sorting with case-insensitive comparison using a compareFunction.
javascript
const fruits = ['banana', 'Apple', 'cherry', 'apple']; // Default sort (case-sensitive) fruits.sort(); console.log('Default sort:', fruits); // Case-insensitive sort fruits.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); console.log('Case-insensitive sort:', fruits);
Output
Default sort: [ 'Apple', 'apple', 'banana', 'cherry' ]
Case-insensitive sort: [ 'apple', 'Apple', 'banana', 'cherry' ]
Common Pitfalls
By default, sort() compares strings based on Unicode values, which can lead to unexpected order especially with uppercase and lowercase letters.
Also, sorting numbers as strings can cause wrong order (e.g., '10' comes before '2').
To fix this, use a compareFunction like localeCompare() for strings or a numeric comparison for numbers.
javascript
const names = ['bob', 'Alice', 'alice', 'Bob']; // Wrong: default sort is case-sensitive names.sort(); console.log('Wrong sort:', names); // Right: case-insensitive sort names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); console.log('Right sort:', names);
Output
Wrong sort: [ 'Alice', 'Bob', 'alice', 'bob' ]
Right sort: [ 'alice', 'Alice', 'bob', 'Bob' ]
Quick Reference
- array.sort(): Sorts array elements as strings in ascending Unicode order.
- compareFunction: Optional function to define custom sort order.
- localeCompare(): Useful for case-insensitive or locale-aware string sorting.
Key Takeaways
Use
array.sort() to sort strings alphabetically in JavaScript.Default sort is case-sensitive and based on Unicode values.
Use a
compareFunction with localeCompare() for case-insensitive sorting.Always test sorting when strings have mixed cases or special characters.
Sorting modifies the original array in place.