--- title: Intl.Collator.prototype.compare slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare tags: - Collator - Internationalization - Intl - JavaScript - Method - Prototype translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare ---
Intl.Collator.prototype.compare() メソッドは、2つの文字列をこの {{jsxref("Collator")}} オブジェクトのソート順に従って比較します。
collator.compare(string1, string2)
string1string2compare ゲッター関数は、 string1 と string2 をこの {{jsxref("Collator")}} オブジェクトのソート順に従って比較した結果を数値で返します。 string1 が string2 の前にくる場合は負の値、 string1 が string2 の後にくる場合は正の値、等しいとみなされる場合は 0 を返します。
配列の並べ替えのために compare ゲッター関数を使用します。なお、この関数は、取得元の collator にバインドされているので、直接 {{jsxref("Array.prototype.sort()")}} に渡すことができます。
var a = ['Offenbach', 'Österreich', 'Odenwald'];
var collator = new Intl.Collator('de-u-co-phonebk');
a.sort(collator.compare);
console.log(a.join(', '));
// → "Odenwald, Österreich, Offenbach"
配列内の文字列の検索のために compare ゲッター関数を使用します。
var a = ['Congrès', 'congres', 'Assemblée', 'poisson'];
var collator = new Intl.Collator('fr', { usage: 'search', sensitivity: 'base' });
var s = 'congres';
var matches = a.filter(v => collator.compare(v, s) === 0);
console.log(matches.join(', '));
// → "Congrès, congres"
| 仕様書 |
|---|
| {{SpecName('ES Int Draft', '#sec-intl.collator.prototype.compare', 'Intl.Collator.prototype.compare')}} |
{{Compat("javascript.builtins.Intl.Collator.compare")}}