Skip to content
Related Articles

Related Articles

JavaScript intl.collator.prototype.compare() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Aug, 2021
View Discussion
Improve Article
Save Article

This intl.collator.prototype.compare() method basically used to make the comparison between two strings as per the sorting order of the collator object.

Here the compare-getter function gives a number as first-string and second-string compared between two strings as per the sorting order of the collator object, It shows a value less than 0 if the first string comes before the second string, shows a value greater than 0 if the first string comes after the second string and 0 if both the parametric strings are equalized.

Syntax:

collator.compare(firststring, secondstring)

Parameters: This method will take two strings (firststring, secondstring) as an input parameter to make the comparison between them.

Example 1: For sorting array using compare-getter function which is bounded to follow the collator which further passed directly to Array.prototype.sort()

Javascript




<script>
  var x = ['Geeks', 'Geeksfor', 'GFG', 'courses', 'java'];
  var collator = new Intl.Collator('de-u-co-phonebk');
 
  // Using collator compare function
  x.sort(collator.compare);
  console.log(x.join(', '));
</script>

Output: 

courses, Geeks, Geeksfor, GFG, java

Example 2: Also use the compare-getter function to search the matching strings between the given parametric strings. Let’s see how:

Javascript




<script>
  var x = ['GFG-for-GFG', 'stress', 'Care', 'surprise', 'gfg'];
  var collator = new Intl.Collator('fr',
                     { usage: 'search', sensitivity: 'base' });
 
  var srch = 'gfg';
  var mtchs = x.filter(n => collator.compare(n, srch) === 0);
  console.log(mtchs.join(', '));
</script>

Output: 

gfg

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!