JavaScript Intl Collator compare() Method
Last Updated :
24 May, 2023
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 input parameters 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' );
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
Supported Browsers:
- Google Chrome 1 and above
- Internet Explorer 3 and above
- Firefox 1 and above
- Apple Safari 1 and above
- Opera 4 and above
- Edge 12 and above
We have a complete list of Javascript Intl methods, to check those please go through this JavaScript Intl Complete Reference article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Share your thoughts in the comments
Please Login to comment...