Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 416
Przemek eS Avatar asked Nov 17 '25 20:11

Przemek eS


1 Answers

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>
like image 71
nikoshr Avatar answered Nov 19 '25 10:11

nikoshr