localeCompare()

The localeCompare() method in Apps Script is used to compare two strings in the current locale, and returns a value indicating whether the first string comes before, after, or is equal to the second string. It takes one argument: the string to compare with the calling string.

Example 1: Comparing Country Names
Suppose we have two country names, “Canada” and “Australia”, and we want to compare them to see which comes first in alphabetical order according to the current locale. We can use the localeCompare() method like so:

var str1 = "Canada";
var str2 = "Australia";
var result = str1.localeCompare(str2);
Logger.log(result);

In this example, we define two strings str1 and str2 containing the country names we want to compare. We use the localeCompare() method on str1, passing str2 as the argument, to compare the two strings. The method returns a value of -1, indicating that str1 comes before str2 in alphabetical order according to the current locale.

Example 2: Comparing City Names
Suppose we have a list of city names in a Google Sheet, and we want to sort them in alphabetical order according to the current locale. We can use the sort() method along with the localeCompare() method like so:

function sortCities() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cities = sheet.getRange("A1:A10").getValues().flat();
  cities.sort(function(a, b) {
    return a.localeCompare(b);
  });
  sheet.getRange("A1:A10").setValues(cities.map(function(city) {
    return [city];
  }));
}

In this example, we use the getActiveSpreadsheet() and getActiveSheet() methods to get a reference to the current Google Sheet. We use the getRange() and getValues() methods to extract the city names from cells A1 to A10 on the sheet, and assign the result to an array cities. We use the sort() method on the cities array, passing a comparison function that uses the localeCompare() method to compare the two strings. Finally, we use the setValues() method to write the sorted cities back to the sheet.

By using the localeCompare() method in Apps Script, we can compare strings in the current locale and perform tasks such as sorting, searching, and more.