user427969
user427969

Reputation: 3896

extjs - Sort store alphanumerically and case insensitively

I want to sort store (ArrayStore and GroupingStore) alphanumerically and case INSENSITIVELY. I am using singleSort() method but it sorts case sensitively.

For example,

data = ['c', '1', 'A', 'a', 'C']
output = ['1', 'A', 'C', 'a', 'c']
myoutput = ['1', 'a', 'A', 'c', 'C'] or [['1', 'A', 'a', 'C', 'c']    // This is what I want

Any suggestion on how to achieve this?

Upvotes: 6

Views: 17387

Answers (4)

Nazar Vynnytskyi
Nazar Vynnytskyi

Reputation: 4727

transform: function (displayName) { return displayName.toLowerCase(); }

store:
   fields:         ['value', 'displayName'],
   data:           [],
   sorters: [{
       property:   'displayName',
       direction:  'ASC',
       transform:  function (displayName) { return displayName.toLowerCase(); }
   }]

Upvotes: 5

user427969
user427969

Reputation: 3896

For 3.2.0 I had to override createSortFunction function as follows:

Ext.override(Ext.data.Store, {
// override
createSortFunction : function(field, direction) {
    direction = direction || "ASC";
    var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
    var sortType = this.fields.get(field).sortType;

    //create a comparison function. Takes 2 records, returns 1 if record 1 is greater,
    //-1 if record 2 is greater or 0 if they are equal
    return function(r1, r2) {
        var v1 = sortType(r1.data[field]),
            v2 = sortType(r2.data[field]);

        // To perform case insensitive sort
        if (v1.toLowerCase) {
            v1 = v1.toLowerCase();
            v2 = v2.toLowerCase();
        }

        return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0));
    };
} 
});

Hope this helps someone.

Upvotes: 6

Duncan
Duncan

Reputation: 231

I found a much simpler way

using ExtJS 3.3.1, probably works with earlier too.

Simply define the sortType for the field as asUCString, like this:

new Ext.data.JsonStore({ 
   url: 'my.php', 
   fields: [{name:'name', sortType:Ext.data.SortTypes.asUCString}], 
   sortInfo: { field: 'name', direction: 'ASC'} 
});

Upvotes: 19

It Grunt
It Grunt

Reputation: 3378

Add this to your code... be wary of your scopes because you will make all sorts on the page case insensitive. I found this code on the forums and have used it successfully in 3.2.1.

Ext.data.Store.prototype.sortData = function(f, direction){
direction = direction || 'ASC';
var st = this.fields.get(f).sortType;
var fn = function(r1, r2) {
    var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
    // ADDED THIS FOR CASE INSENSITIVE SORT
    if (v1.toLowerCase) {
        v1 = v1.toLowerCase();
        v2 = v2.toLowerCase();
    }
    return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
};
this.data.sort(direction, fn);
if (this.snapshot && this.snapshot != this.data) {
    this.snapshot.sort(direction, fn);
}

}

Upvotes: 6

Related Questions