Sort Strings with localeCompare()
Write a JavaScript function that takes two strings and uses localeCompare() to determine their alphabetical order. Return -1 if the first string comes before the second, 0 if they are equal, or 1 if the first comes after the second.
String.prototype.localeCompare() is a method that compares two strings according to locale-specific sort order. It returns a negative number if the reference string occurs before the compare string, positive if after, and 0 if they are equal. This is the standard way to implement custom sort comparators for strings.
Unlike simple < and > operators which compare UTF-16 code unit values, localeCompare() respects linguistic conventions: it handles accented characters (é comes after e), case-insensitive comparisons, and language-specific sorting rules. It accepts optional locale and options parameters for fine-grained control.
Time complexity is O(n) where n is the length of the shorter string. Space complexity is O(1). The method is essential for creating sort comparators: arr.sort(function(a,b) { return a.localeCompare(b); }).
Edge cases include identical strings (returns 0), empty strings, strings with numbers, case sensitivity (uppercase vs lowercase), and special characters.
Example Input & Output
apple comes before banana
Same strings are equal
Shorter string comes first
banana comes after apple
z comes after a
Algorithm Flow
Solution Approach
Compare two strings according to locale-specific rules using localeCompare(). Returns a negative number if the reference string comes before the compare string, positive if after, and 0 if equal.
localeCompare() handles language-specific sorting (accented characters, special cases). For case-insensitive comparison, add { sensitivity: 'base' } as the second argument.
Time O(n), Space O(1).
Best Answers
function solution(a, b) {
if (a.localeCompare(b) < 0) return -1;
if (a.localeCompare(b) > 0) return 1;
return 0;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
