简体   繁体   中英

How to sort the table by date if the date is not filled everywhere?

** not working:**

I am using react-table, what am I doing wrong? I am currently using version 7 of the plugin.

 {
        Header: 'DATE',
        accessor: 'DATE',
        sortType: (rowA, rowB) => {
            const a = rowA.values.DATE;
            const b = rowB.values.DATE;

            if (a !== null && b !== null) {
                const dateA = getDate(a);
                const dateB = getDate(b);

                if (dateA === dateB) {
                    return 0;
                }

                if (dateB > dateA) {
                    return 1;
                } else {
                    return -1;
                }
            } else {
                return 0;
            }
        },
    },

You are returning 0 when even one of them is null . You could first sort based on whether the dates are null. Move the nulls to the end. Then, sort them based on the actual date value (Assuming getDate returns Date objects)

sortType: (rowA, rowB) => {
  const a = rowA.values.DATE,
        b = rowB.values.DATE;

  return (a === null) - (b === null) 
          || getDate(a) - getDate(b)
})

Here's a snippet:

 const array = [null, "2/1/2021", "1/1/2021", null, "3/1/2021"] array.sort( (a, b) => (a === null) - (b === null) || new Date(a) - new Date(b) ) console.log(array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM