Sort columns by icons

Sort columns by icons

fuqingfuqing Posts: 1Questions: 1Answers: 0

I have a table, some cells contains icons. What I want to achieve here is that when applying sorting on any column, I want the cells with icons to take priority, and to appear either on the top or bottom.
I have noticed that if the cell content is icon + numbers, the sort works exactly the way I want.
However when the cell contains icon + letters, the sort always work in alphabetic order regardless of the icon. Did anyone have a solution for this?

Answers

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    You can try the Natural Sorting Plugin. It sorts data with a mix of letters and numbers.

    Kevin

  • Tester2017Tester2017 Posts: 145Questions: 23Answers: 17
    edited October 2017

    You can create your own sorting algorithm with the extension $.fn.dataTable.ext.order.

    The next one I use to sort field1 on a fa icon:

    $.fn.dataTable.ext.order[`dom-class`] = function(settings, col)
    {
        return this.api().column(col, {order:`index`}).nodes().map(function(td, i)
        {
            return $(`i`, td).hasClass(`fa-check`) ? `1` : `0`;
        });
    }
    

    And in your table declaration you will do this:

    columns: [
        {data: `field1`, orderDataType: `dom-class`},
        {data: `otherField`}
    ],
    

    So what you have to do is change the return value return $(`i`, td).hasClass(`fa-check`) ? `1` : `0`; to your demands. And of course you can change the name dom-class as it is only an arbitrary name you are giving to your own sort type.

This discussion has been closed.