Export (0) Print
Expand All

compare Property (Intl.Collator)

Returns a function that compares two strings by using the collator’s sort order.

collatorObj.compare

collatorObj

Required. The name of the Collator object to use for the comparison.

The function returned by the compare property takes two arguments, x and y, and returns the result of a locale-specific comparison of x and y by using the options specified in the Collator object.

The result of the comparison will be:

  • -1 if x is before y in the sort order.

  • 0 (zero) if x is equal to y in the sort order.

  • 1 if x is after y in the sort order.

The following example creates a Collator object and performs a comparison.

var co = new Intl.Collator(["de-DE-u-co-phonebk"]);

if (console && console.log) {
    console.log(co.compare("a", "b")); // Returns -1
}

The following example uses Collator objects to sort an array. This example shows locale-specific differences.

var co1 = new Intl.Collator(["de-DE-u-co-phonebk"]);
var co2 = new Intl.Collator(["de-DE"]);
var co3 = new Intl.Collator(["en-US"]);

var arr = ["ä", "ad", "af", "a"];

if (console && console.log) {
    console.log(arr.sort(co1.compare));  // Returns a,ad,ä,af
    console.log(arr.sort(co2.compare));  // Returns a,ä,ad,af
    console.log(arr.sort(co3.compare));  // Returns a,ä,ad,af
}

The following example uses a Collator object to search for a string.

// String to search
var arr = ["ä", "ad", "af", "a"];
// String searched for
var s = "af";

var co = new Intl.Collator("de-DE", { usage: "search" });
var matches = arr.filter(function (i) {
    return co.compare(i, s) === 0;
});

if (console && console.log) {
    console.log(matches);  // Returns af
}

Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). See Version Information. Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported in Windows 8.

Show:
© 2014 Microsoft