Problem:
I am having some trouble with sorting the addresses in my table. I would like to have them sort like this
800 E Maine Ave
801 E Maine Ave
802 E Maine Ave
7341 E Main St
7359 E Main St
7390 E Main St
but instead it is coming out like this
Here is the code I am using to sort the table. I have it when the caret is hit that it knows to sort by ascending or descending based on how it is pointed
function SetDataTable() {
const tablerowsResult = document.querySelectorAll('#Resultbody tr'),
tableheadingsResult = document.querySelectorAll('#ResultTable thead th.click');
tableheadingsResult.forEach((head, i) => {
let sortasc = true;
head.onclick = () => {
tableheadingsResult.forEach(head => head.classList.remove('active'));
head.classList.add('active');
document.querySelectorAll('td').forEach(td => td.classList.remove('active'))
tablerowsResult.forEach(row => {
row.querySelectorAll('td')[i].classList.add('active')
})
head.classList.toggle('asc', sortasc);
sortasc = head.classList.contains('asc') ? false : true;
sortTableResult(i, sortasc);
}
})
}
function sortTableResult(col, sortasc) {
const tablerowsResult = document.querySelectorAll('#Resultbody tr');
[...tablerowsResult].sort((a, b) => {
let firstrow = a.querySelectorAll('td')[col].textContent.toLowerCase();
let secondrow = b.querySelectorAll('td')[col].textContent.toLowerCase();
return sortasc ? (firstrow < secondrow ? 1 : -1) : (firstrow < secondrow ? -1 : 1);
}).map(sortedrow => document.querySelector('#Resultbody').appendChild(sortedrow));
}
Solution:
This should sort rows the way you want:
function sortTableResult(col, sortasc) {
const tablerowsResult = document.querySelectorAll('#Resultbody tr');
[...tablerowsResult].sort((a, b) => {
let firstrow = Number(a.querySelectorAll('td')[col].textContent.toLowerCase().split(' ')[0]);
let secondrow = Number(b.querySelectorAll('td')[col].textContent.toLowerCase().split(' ')[0]);
return sortasc ? (firstrow < secondrow ? 1 : -1) : (firstrow < secondrow ? -1 : 1);
}).map(sortedrow => document.querySelector('#Resultbody').appendChild(sortedrow));
}
As I understand you want to sort addresses based on numeric values, so in this code I split the address with .split(' ')
and then took first element, which is the one with a numeric value, and converted it to number.