React-Bootstrap-Table-Next Sort Alphanumeric Strings on Dynamic Table

Viewed 650

I have a dynamic table that generates 70+ columns in React-Bootstrap-Table-Next. I'm running into a problem trying to sort the columns in alphanumerical order (some columns are numbers and some columns are letters). The data being fed into the columns are all strings. I'm using the sortFunc but of course it only sorts columns that are numerical strings. How can I get the sortFunc to sort both?

This is my function I have tried. Checkout the sortFunc.

let columns = [];
let headers = Object.keys(this.props.reconDetails[0]); //creating the text for headers
const newColumn = {
   dataField: header,
   text: header,
   sort: true,
   sortFunc: (a, b, order, dataField) => {
      if (order === 'asc') {
          return b - a;
      }
       return a - b;
      };
   columns.push(newColumn);
   this.setState({
     columns
   })
}

Bootstrap Table:

BootstrapTable
   striped
   headerClasses="tableHeader"
   classes="tableBody"
   wrapperClasses="table-responsive"
   keyField={"Case_Line_Number"}
   data={this.state.RECON_DETAIL}
   columns={this.state.columns}
   />
1 Answers

Found the answer here as it explains it well. The author utilized the localeCompare method. http://fuzzytolerance.info/blog/2019/07/19/The-better-way-to-do-natural-sort-in-JavaScript/

I solved my problem below:

sortFunc: (a, b, order, dataField) => {
   if (order === 'asc' || !order) {
       return b.localeCompare(a, navigator.languages[0] || navigator.language, {numeric: true, ignorePunctuation: true});
       }
       return a.localeCompare(b, navigator.languages[0] || navigator.language, {numeric: true, ignorePunctuation: true});
       },
Related