Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]);};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    ]}
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading