3

I have a collection of data:

["Alphabet","Zend","Ćwiczenia"]      

as result collection.sort I get: ["Alphabet","Zend","Ćwiczenia"].

How to overload comparator to sort with UTF-8 and different locales?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Przemek eS
  • 1,224
  • 1
  • 8
  • 21

1 Answers1

2

You need to set up a comparator method on your collection that uses localeCompare as its sort function.

Assuming your collection looks like

var c = new C([
    {name: "Alphabet"},
    {name: "Zend"},
    {name: "Ćwiczenia"}
]);

it would look like

var C = Backbone.Collection.extend({
    comparator: function(a, b) {
        return a.get('name').localeCompare(b.get('name'));
    }
});

and a demo

var C = Backbone.Collection.extend({
    comparator: function(a, b) {
        return a.get('name').localeCompare(b.get('name'));
    }
});

var c = new C([
    {name: "Alphabet"},
    {name: "Zend"},
    {name: "Ćwiczenia"}
]);
console.log(c.pluck('name'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • Great its works. But have other problem. The time of sort with default comparator is 0,5s , but with your comparator ~4s. Its a way to speed up the process ? – Przemek eS Dec 20 '16 at 13:01
  • You'll have to look up how to speed up locale sorts in JS. http://stackoverflow.com/questions/14677060/400x-sorting-speedup-by-switching-a-localecompareb-to-ab-1ab10 could get you started – nikoshr Dec 20 '16 at 13:10
  • @ThePrzemyslaw94 I would recommend that you define a [Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) before you define your Backbone.Collection. Something like: `var collator = new Intl.Collator(navigator.language, { sensitivity: 'base' })`. Then inside your comparator function you'd do: `return collator.compare(a.get('name'), b.get('name'))` – idbehold Dec 20 '16 at 16:47
  • @idbehold,@nikoshr --Firstly thanks to help me. I try this method but compare to put on ice my select for over 4 second and page dont works . Maybe a way to asynchronic sort ? – Przemek eS Dec 22 '16 at 09:08