Search code examples
javascriptextjsextjs7-classic

EXTJS- Grid column sorting - sort the null values of columns at the bottom of the grid


enter image description here

While sorting the EmpNo column either ASC/DESC, null values should be avoided so that it will be at the end of the grid.

This code just helped to reverse the sorting logic:

if(v1 < v2 || !v1) {
    return -1;
 }
        
 if(v1 > v2 || !v2) {
     return 1;
 }
        
 return 0;

Solution

  • Here is a sample code. With this modification, the null values of the 'empNo' column will be sorted at the bottom of the grid when you click on the column header to sort.

    Ext.create('Ext.data.Store', {
            storeId: 'simpsonsStore',
            fields: ['name', 'email', 'phone'],
            data: [{
                EmpNo: 3,
                name: 'Lisa',
                email: '[email protected]',
                phone: '555-111-1224'
            }, {
                EmpNo: 2,
                name: 'Bart',
                email: '[email protected]',
                phone: '555-222-1234'
            }, {
                EmpNo: null,
                name: 'Homer',
                email: '[email protected]',
                phone: '555-222-1244'
            }, {
                EmpNo: 1,
                name: 'Marge',
                email: '[email protected]',
                phone: '555-222-1254'
            }, {
                EmpNo: null,
                name: 'george',
                email: '[email protected]',
                phone: '555-222-1244'
            }]
        });
        
        Ext.create('Ext.grid.Panel', {
            title: 'Simpsons',
            store: Ext.data.StoreManager.lookup('simpsonsStore'),
            columns: [{
                text: 'EmpNo',
                flex: 1,
                dataIndex: 'EmpNo',
                sorter: function (data1, data2) {
                    var empNo1 = data1.get('EmpNo'),
                        empNo2 = data2.get('EmpNo'),
                        direction = this.getDirection();
        
                    if (empNo1 == empNo2) {
                        return 0;
                    }
                    if (empNo1 === null) {
                        return direction == 'ASC' ? 1 : -1;
                    }
        
                    if (empNo2 === null) {
                        return direction == 'ASC' ? -1 : 1;
                    }
        
                    return empNo1 > empNo2 ? 1 : -1;
                }
            }, {
                text: 'Name',
                dataIndex: 'name'
            }, {
                text: 'Email',
                dataIndex: 'email',
                flex: 1
            }, {
                text: 'Phone',
                dataIndex: 'phone'
            }],
            height: 400,
            width: 500,
            renderTo: Ext.getBody()
        });