0

I have difficulties for completing an emerging task. I must implement a table in which some columns must have two fields. These columns must have a sorting functionality through which the user will be able to sort the selected fields. To be more accurate, see the screenshot below:

enter image description here

You can see the columns which contains two fields. When, the user clicks in a field, arrows must be shown and the grid will be sorted by the selected value. When the user clicks the other fields (Price for example), arrows are shown, the field becomes bold and the grid is sorted by the selected field.

I use Griddle but, how can I implement in Griddle such a functionality? Should I make my own grid from scratch?

tomahh
  • 13,441
  • 3
  • 49
  • 70
RamAlx
  • 6,976
  • 23
  • 58
  • 106
  • What do you want to achieve? Sorting by multiple columns? – Michal Cumpl Jan 30 '17 at 09:50
  • I want to sort all the table, taking into consideration the field through which i choose to sort – RamAlx Jan 30 '17 at 10:40
  • So you wish to sort it by one column only? Griddle supports this. – Michal Cumpl Jan 30 '17 at 11:03
  • Yes i know this, but the question is different, you can see the layout about. Check the 2nd columns. It contains two fields.When, the user clicks the first field, arrows must be shown and the grid will be sorted by the selected value. When the user clicks the other fields (Last Close), arrows are shown, the field becomes bold and the grid is sorted by the selected field. – RamAlx Jan 30 '17 at 11:56
  • Is sorting by multiple columns supported on this grid/react-data-table? – Vaibhav More Jun 24 '20 at 09:19

1 Answers1

1

This will sort any column if you have stored your data in the state and the data is either a string, number or boolean.

function sortFunc(a, b, key) {
  
  if (typeof(a[key]) === 'number') {
    return a[key] - b[key];
  } else if (typeof(a[key]) === 'boolean') {
    return a[key] ? 0 : 1;
  }

  const ax = [];
  const bx = [];

  a[key].replace(/(\d+)|(\D+)/g, (_, $1, $2) => { ax.push([$1 || Infinity, $2 || '']); });
  b[key].replace(/(\d+)|(\D+)/g, (_, $1, $2) => { bx.push([$1 || Infinity, $2 || '']); });

  while (ax.length && bx.length) {
    const an = ax.shift();
    const bn = bx.shift();
    const nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
    if (nn) return nn;
  }

  return ax.length - bx.length;
}

function sortByColumn(column, data) {
      const isAsc = this.state.sortHeader === column ? !this.state.isAsc : true;
      const sortedData = data.sort((a, b) => sortFunc(a, b, column));

      if (!isAsc) {
        sortedData.reverse();
      }

      this.setState({
        data: sortedData,
        sortHeader: column,
        isAsc
      });
  }
<IconButton onClick={() => this.sortByColumn(column.key, this.state.data)} style={styles.sortButton} >
  <SortIcon />
</IconButton>
Nathan Hensher
  • 329
  • 3
  • 8