NOTE

“I used localeCompare() because it provides lexicographical ordering for strings, is more readable than manual comparisons, and correctly handles locale-specific sorting rules. For interview problems involving alphabetical ordering such as Reconstruct Itinerary, it’s a clean and idiomatic solution.”

JavaScript localeCompare()

What is it?

localeCompare() compares two strings according to language-specific sorting rules and returns:

  • < 0 → current string comes before target string
  • 0 → strings are equal
  • > 0 → current string comes after target string

Why is it Important?

Using <, >, or default sort() performs simple Unicode comparison, which may produce incorrect alphabetical ordering for different languages, accents, numbers, and case sensitivity.

localeCompare() provides:

  • Correct alphabetical sorting
  • Locale-aware comparisons (English, German, French, etc.)
  • Case-insensitive sorting
  • Numeric sorting support

Basic Example

const fruits = ["banana", "apple", "orange"];
 
fruits.sort((a, b) => a.localeCompare(b));
 
console.log(fruits);
// ["apple", "banana", "orange"]

Case-Insensitive Sorting

const names = ["john", "Alice", "bob"];
 
names.sort((a, b) =>
  a.localeCompare(b, undefined, { sensitivity: "base" })
);
 
console.log(names);
// ["Alice", "bob", "john"]

Numeric Sorting

Without numeric: true:

["10", "2", "1"].sort();
// ["1", "10", "2"]

With localeCompare():

["10", "2", "1"].sort((a, b) =>
  a.localeCompare(b, undefined, { numeric: true })
);
 
// ["1", "2", "10"]

Interview Usage

Most commonly used for:

arr.sort((a, b) => a.localeCompare(b));

Examples:

  • Reconstruct Itinerary (lexicographical ordering)
  • Sorting names/titles
  • User-facing alphabetical lists
  • Locale-aware search and filtering

Complexity

For sorting n strings:

  • Time: O(n log n * k)
    • k = average string length
  • Space: Depends on JS engine’s sort implementation

Interview Takeaway

Use localeCompare() whenever strings need to be sorted lexicographically or alphabetically in a user-friendly way. It handles locale rules, case sensitivity, and numeric comparisons better than default string comparison.