[SalesForce] Get column header label while sorting a lightning:datatable column

As per the salesforce official doc, when we sort a column, we can get the field name by using

var fieldName = event.getParam('fieldName');

https://developer.salesforce.com/docs/component-library/bundle/lightning:datatable/documentation

({
    // Client-side controller called by the onsort event handler
    updateColumnSorting: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        // assign the latest attribute with the sorted column fieldName and sorted direction
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName, sortDirection);
    }
    })

Is there any way we can get the column header label?

UPDATED :

I somehow found the workaround, but still looking an for the easy way.

updateColumnSorting: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var labelName = '';
        var colList = cmp.get("v.myCols");
        colList.some(function(col){
            if(col.fieldName === fieldName) {
               labelName = col.label; 
            }
            return col.fieldName === fieldName;
        });
        var sortDirection = event.getParam('sortDirection');
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName,labelName, sortDirection);
    }

Best Answer

You use Array.prototype.find to find the column based on the incoming fieldName:

var columns = cmp.get("v.columns"), // whatever you called the columns attribute
    fieldName = event.getParam("fieldName"),
    sortByCol = columns.find(column => fieldName === column.fieldName),
    fieldLabel = sortByCol.label;

At this point, you have all the attributes from the column header (sortByCol) and the field label, as you've asked for.