How to Sort Strings in JavaScript
Sorting strings in JavaScript is pretty straightforward with the Array.prototype.sort()
method. This sorts the elements of an array in place. It also returns the sorted array. Keep reading to learn how to easily sort strings with the Array.prototype.sort()
.
What is basic sort in JavaScript?
To perform a basic alphabetical sort, call the sort()
method on your array of strings.
const fruits = ['Banana', 'Orange', 'Apple', 'Mango']; fruits.sort(); console.log(fruits); // Outputs: ['Apple', 'Banana', 'Mango', 'Orange']
This method directly sorts the array alphabetically. As you can see it works well for straightforward sorting tasks.
How to sort with localeCompare
in JavaScript?
To sort strings considering different locales and case sensitivity, apply the localeCompare
function within the sort's compare function.
const items = ['résumé', 'Resume', 'resumé', 'résume']; items.sort((a, b) => a.localeCompare(b)); console.log(items); // Outputs: ['resumé', 'Resume', 'résume', 'résumé']
Using localeCompare
makes sure that the sort accounts for various local settings and special characters, making your application more globally adaptable.
Customizing sort order
You can define a custom sort order by providing a compare function. This approach is beneficial for implementing sorting rules beyond simple alphabetical organization.
const names = ['John', 'jane', 'Bob', 'bob']; names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); console.log(names); // Outputs: ['Bob', 'bob', 'jane', 'John']
Here, converting each string to lowercase before comparing them achieves a case-insensitive sort, illustrating how you can tailor sorting logic to specific requirements.
Sorting by length
Sort strings by their length by using a compare function tailored to evaluate string lengths. This method is particularly useful when the order of strings by size is more relevant than their alphabetical order.
const words = ['Banana', 'Apple', 'Mango', 'Orange', 'Peach']; words.sort((a, b) => a.length - b.length); console.log(words); // Outputs: ['Apple', 'Mango', 'Peach', 'Banana', 'Orange']
This example demonstrates sorting strings by increasing length, allowing for a quick and effective organization of data based on size.
Mastering these sorting techniques allows developers to efficiently manage and present string data in JavaScript, enhancing the user experience and data handling capabilities of their applications.
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper
How to Convert a String to a Date in JavaScript
Max Musing