I am trying to sort a column of a HTML table containing comma values. I know how to sort values, but I am not sure how to sort the numbers having comma values.
In the below example, if we click on the header "size", it has to sort by either ascending or descending order, but it's not sorting as expected. Please help me on this. Thank you so much in advance.
HTML
<table>
<tr><th>Country</th><th>Date</th><th>Size</th></tr>
<tr><td>France</td><td>2001-01-01</td><td><i>95,000</i></td></tr>
<tr><td><a href=#>spain</a></td><td><i>2005-05-05</i></td><td>1,850,000</td></tr>
<tr><td><b>Lebanon</b></td><td><a href=#>2002-02-02</a></td><td>37,000</td></tr>
<tr><td><i>Argentina</i></td><td>2005-04-04</td><td>100,000</td></tr>
<tr><td>USA</td><td></td><td>6,000</td></tr>
</table>
JS
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) );
})));
CSS
table, th, td {
border: 1px solid black;
}
th {
cursor: pointer;
}
You can find the previous answer for sorting but not for comma values in the below link.