'React Sort Table Rows by Id
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>
}
Solution 1:[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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | guiwme5 |
| Solution 2 | Riya Adhikari |
