Search code examples
javascriptreactjssortingantd

Sort null value in Ant Design Table with ReactJS


I'm using the antdesign table in ReactJS to display numerical data. There are null values in the columns, which are causing issues with the sorting function. The problem is that I would like the null values to always be displayed at the end of the table regardless of the sorting direction, but unfortunately, I can only achieve this in one direction. What am I doing wrong?

The custom sorting function I tried is:

const customSorter = (a, b,col) => {
    
    if (a[col] === null && b[col] === null) {
      return 0;
    } else if (a[col] === null) {
      return -1;
    } else if (b[col] === null) {
      return 1;
    }
  
    return parseFloat(a[col]) - parseFloat(b[col]);};

Solution

  • You need to modify the conditions so whether the sort is in ascending or descending order, pushing null values to the end in both cases.

    const customSorter = (a, b, col, sortOrder) => {
        if (a[col] === null && b[col] === null) {
            return 0;
        } else if (a[col] === null) {
            return 1;  // Push `a` with null at the end
        } else if (b[col] === null) {
            return -1; // Push `b` with null at the end
        }
    
        const numA = parseFloat(a[col]);
        const numB = parseFloat(b[col]);
        return sortOrder === 'ascend' ? numA - numB : numB - numA;
    };
    

    JSX

    <Table
        dataSource={dataSource}
        columns={[
            {
                title: 'Number',
                dataIndex: 'number',
                key: 'number',
                sorter: (a, b, sortOrder) => customSorter(a, b, 'number', sortOrder),
                sortDirections: ['ascend', 'descend'],
            },
            // other columns
        ]}
    />