I'm having an issue sorting my HTML table. The headers are clickable and they do sort, however it doesn't sort the table correctly. I'm using ACF Pro and FacetWP. The table is dynamic with PHP, need this to be able to sort alphanumerically. In theory this sort algorithm should work, but I'm not understanding why it's not sorting correctly. Any help would be greatly appreciated. Thank you!
cPrev = -1; // global var saves the previous c, used to
// determine if the same column is clicked again
function sortBy(c) {
rows = document.getElementById("sortable").rows.length; // num of rows
columns = document.getElementById("sortable").rows[0].cells.length; // num of columns
arrTable = [...Array(rows)].map(e => Array(columns)); // create an empty 2d array
for (ro = 0; ro < rows; ro++) { // cycle through rows
for (co = 0; co < columns; co++) { // cycle through columns
// assign the value in each row-column to a 2d array by row-column
arrTable[ro][co] = document.getElementById("sortable").rows[ro].cells[co].innerHTML;
}
}
th = arrTable.shift(); // remove the header row from the array, and save it
if (c !== cPrev) { // different column is clicked, so sort by the new column
arrTable.sort(
function(a, b) {
if (a[c] === b[c]) {
return 0;
} else {
return (a[c] < b[c]) ? -1 : 1;
}
}
);
} else { // if the same column is clicked then reverse the array
arrTable.reverse();
}
cPrev = c; // save in previous c
arrTable.unshift(th); // put the header back in to the array
// cycle through rows-columns placing values from the array back into the html table
for (ro = 0; ro < rows; ro++) {
for (co = 0; co < columns; co++) {
document.getElementById("sortable").rows[ro].cells[co].innerHTML = arrTable[ro][co];
}
}
}
<body>
<div style="overflow-x:auto;">
<table id="sortable" style="width:100%;">
<thead>
<tr style="cursor:pointer">
<th align="left">Address</th>
<th onclick="sortBy(1)" align="left">City</th>
<th onclick="sortBy(2)" align="left">State</th>
<th onclick="sortBy(3)" align="left">Type</th>
<th onclick="sortBy(4)" align="right">Available SF</th>
</tr>
</thead>
<tbody id="table-body">
<?php while ( have_posts() ): the_post(); ?>
<tr>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('building_address'); ?>
</a>
</td>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('city'); ?>
</a>
</td>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('state'); ?>
</a>
</td>
<td align="left">
<?php echo get_the_term_list($post->ID, 'property_type', '', ', '); ?>
</td>
<td align="right">
<a href="<?php the_permalink(); ?>">
<?php the_field('max_available_size'); ?>
</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
return (a[c] < b[c]) ? -1 : 1;withreturn (a[c]+'').localeCompare(b[c]);