0

Comparing Strings Lexicographically in JavaScript

To compare strings alphabetically, we can use localeCompare() method. This function returns a negative value if the reference string is lexicographically (alphabetically) before the compared string (the parameter), a positive value if it comes afterwards, and a value of 0 if they are equal.

var a = "hello";
var b = "world";

console.log(a.localeCompare(b)); // -1


var arr = ["bananas", "cranberries", "apples"];
arr.sort((a, b) => a.localeCompare(b));

console.log(arr); // [ "apples", "bananas", "cranberries" ]
RUN
add comment
Suggest a different solution or add another example