3

Is it possible to create a custom Intl.Collator object for Javascript? Suppose I have:

var letters = [ "a", "n", "ñ", "x" ]

If I sort them, the ñ will go to the end by default:

letters.sort() // [ "a", "n", "x", "ñ" ]

However, using the new Intl.Collator, I can do:

letters.sort(Intl.Collator('es').compare)

Which sorts by Spanish (es) rules, and puts the ñ after n.

[ "a", "n", "ñ", "x" ] 

Now, suppose for some reason I wanted to write a Collator of my own, that would put the ñ first?

[ "ñ", "a", "n", "x" ] 

I haven’t been able to find any information about customizing a new rule set for Intl.Collator.

Is this possible?

Update

Yes, it is possible.

Update:

I have found advice in the ECMAscript i18n standard2 on how to create custom locales:

function MyCollator​(locales, options) {
  Intl​.Collator​.call​(this, locales, options);
  // initialize MyCollator properties
}
MyCollator​.prototype = Object​.create​(Intl​.Collator​.prototype);
MyCollator​.prototype​.constructor = MyCollator;
// add methods to MyCollator​.prototype
var collator = new MyCollator​("de-u-co-phonebk");
a​.sort​(collator​.compare);
  • 1
    Do you want to define an arbitrary order for arbitrary symbols? – cdosborn Mar 25 '15 at 01:36
  • 1
    I recently made a new [tag:ecmascript-intl] for questions like this but don't want to assume myself which of your current tags it should replace. Use it if you wish. – hippietrail Apr 25 '15 at 01:48

1 Answers1

1

You may be able to get what you want by using the "sensitivity" option.

The Intl.Collator.prototype is not writable.

You may be able to create and array with sort and character to set you own sort order.

$convert[character]= sortOrder ;

Array structure would depend on purpose.
With this structure you'd have to convert the result back again.

$letters = [$convert[a],$convert[n],$convert[ñ],$convert[x]);

This one would probably work best in most cases.

$letters = [[$convert[a],a],[$convert[n],n],[$convert[ñ],[ñ],[$convert[x],x]);
Misunderstood
  • 5,534
  • 1
  • 18
  • 25