I'm trying to sort the table that contains a mix of numbers and alphabet separately per row. How can I sort the inventory volume below
ID | Name | Inventory Volume |
---|---|---|
1 | Rachel | Data is not enough |
2 | Ross | 100 |
3 | Monica | 1 |
4 | Connor | Data is not enough |
5 | Dustin | -5 |
into this sorting example is descending the letter should be the last.
ID | Name | Inventory Volume |
---|---|---|
1 | Ross | 100 |
2 | Monica | 1 |
3 | Connor | -5 |
4 | Rachel | Data is not enough |
5 | Connor | Data is not enough |
I tried to modify the following code below comparing the string but it seems I am doing something wrong
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) =>
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
// do the work...
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.appendChild(tr) );
})));
Reference: Sorting HTML table with JavaScript
I also want the other columns to be sorted.
Could you please show the code on how I could achieve this sorting to modify the following code above? It should sort descending and ascending. Thanks