0

I have a table which displays fields of products from an API. I need the rows to appear in ASC; order. I have seen a couple methods on how to do this using React-Tables but I have it so far set up without any of the hooks so I would prefer to a built in method.

export const Table = ({data}) => {

  const columns = data[0] && Object.keys(data[0])
return <table cellPadding={0} cellSpacing={0}>
<thead>
  <tr>{data[0] && columns.map((heading) => <th>{heading}</th>)}</tr>
  </thead>
  <tbody>
{data.map(row => <tr>
  {
  columns.map(column => <td>{row[column]}</td>)
}
</tr>)}
  </tbody>
</table>
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Yonko
  • 33
  • 7

2 Answers2

1

you just have to sort your data array with sort()... read this: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

an example here => Sort array by firstname (alphabetically) in Javascript

guiwme5
  • 712
  • 6
  • 10
0

Example of a table with 3 sorting states (ascending, descending and unsorted)

  const sortArray = (header) => {
    const newArr = [...initailArr];

    if (sortState === 0) {
      newArr.sort((a, b) => {
        const keyA = a[header];
        const keyB = b[header];
        if (keyA < keyB) return -1;
        if (keyA > keyB) return 1;
        return 0;
      });
      setSortState(1);
    } else if (sortState === 1) {
      newArr.sort((a, b) => {
        const keyA = a[header];
        const keyB = b[header];
        if (keyA > keyB) return -1;
        if (keyA < keyB) return 1;
        return 0;
      });
      setSortState(2);
    } else {
      setSortState(0);
    }
    setSortedArray(newArr);
  };

full working example can be found here https://codesandbox.io/s/async-await-then-study-5yvts?file=/src/Table.js:1483-2126

Riya Adhikari
  • 367
  • 3
  • 7