简体   繁体   中英

How to sort strings and numbers in a same array for a datatable

I am rebuilding a datatable using React with JavaScript so I am sorting some information that includes strings and numbers so I have been trying to implement array.sort(a, b) => a.toLowerCase > b.toLoweCase... etc to sort everything, and at some point it works perfectly until I click the button that sorts the numbers because It gives me an error,

And without tolowercase function that specific sort number section works perfectly but the other ones that have strings with uppercase and lowercase don't sort correctly

How can I solve this problem?

const useSortableData = (data, config = null) => {
const [sortConfig, setSortConfig] = useState(config);

  const sortedItems = useMemo(() => {
    let sortableItems = [...data];
    if (sortConfig !== null) {
      sortableItems.sort((a, b) => {
    const optionA = a[sortConfig.key].toString().toLowerCase()

    const optionB = b[sortConfig.key].toString().toLowerCase()

    if (optionA < optionB) {
      return sortConfig.direction === 'ascending' ? -1 : 1;
    }
    if (optionA > optionB) {
      return sortConfig.direction === 'ascending' ? 1 : -1;
    }
    return 0;
      });
    }
    return sortableItems;
  }, [data, sortConfig]);

  const requestSort = (key) => {
    let direction = 'ascending';
    if (
      sortConfig &&
      sortConfig.key === key &&
      sortConfig.direction === 'ascending'
    ) {
      direction = 'descending';
    }
    setSortConfig({ key, direction });
  };

  return { data: sortedItems, requestSort, sortConfig };
};

Error which I receive when I click the number sort section

TypeError: a[sortConfig.key].toLowerCase is not a function

More clean code

    const optionA = a[sortConfig.key].toString().toLowerCase()

    const optionB = b[sortConfig.key].toString().toLowerCase()

    if (optionA < optionB) {
      return sortConfig.direction === 'ascending' ? -1 : 1;
    }
    if (optionA > optionB) {
      return sortConfig.direction === 'ascending' ? 1 : -1;
    }
    return 0;

Continuing from comment for sorting alphanumerical data: Hope you don't mind me cleaning up a little

  const sortedItems = useMemo(() => {
    let sortableItems = [...data];
    if (sortConfig !== null) {
      sortableItems.sort((a, b) => {
        let aString = a.toString().toLowerCase();
        let bString = b.toString().toLowerCase();

        if (sortConfig.direction === 'descending') {
          return bString.localeCompare(aString, 'en', { numeric: true })
        }
        
        // return default as ascending
        return aString.localeCompare(bString, 'en', { numeric: true })
      });
    }
    return sortableItems;
  }, [data, sortConfig]);

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