Code Logo

Sort Strings with localeCompare()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

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

Example 1
Input
"apple","banana"
Output
-1
Explanation

apple comes before banana

Example 2
Input
"cat","cat"
Output
0
Explanation

Same strings are equal

Example 3
Input
"abc","abcd"
Output
-1
Explanation

Shorter string comes first

Example 4
Input
"banana","apple"
Output
1
Explanation

banana comes after apple

Example 5
Input
"z","a"
Output
1
Explanation

z comes after a

Algorithm Flow

Recommendation Algorithm Flow for Sort Strings with localeCompare()
Recommendation Algorithm Flow for Sort Strings with localeCompare()

Solution Approach

function solution(a, b) {
  if (a.localeCompare(b) < 0) return -1;
  if (a.localeCompare(b) > 0) return 1;
  return 0;
}

Best Answers

javascript - Approach 1
function solution(a, b) {
  if (a.localeCompare(b) < 0) return -1;
  if (a.localeCompare(b) > 0) return 1;
  return 0;
}