Reactjs: how to sort columns if column name is dynamic

I know that to sort a column we use sorter: (a, b) => a.monthName - b.monthName but in my case, my column name (i.e. monthName) is not hardcoded but is generated dynamically as I load the component. So for this my row object looks like:

   November: xyz,
   December: xyz,
   January: xyz,
   forecasted: xyz

I'm adding Nov, Dec, Jan i.e. the names of the months dynamically in the state via

const newColumn = {
        title: monthName,
        dataIndex: monthName,
        key: monthName,
        sorter: (a, b) => a.monthName - b.monthName,
        render(text,record){}
       }

I can't hardcode the month names as I need last 3 months' names. Is there a way I can pass column name to this sort function? How can I sort the columns in this case?


Solution 1:

You could save the column's name into a variable (or in this case state) and address the variable when sorting.

Example:

var columnName = 'monthName';

(a, b) => a[columnName] - b[columnName];