Сортировка в таблице с разным содержанием (текс, числа, смешанное содержание)
Делаю сортировку в таблице на js
Как сделать так что бы сортировалось в зависимости от содержимого, т.е. если текст то сортировка происходит по алфавиту как сейчас в первом столбце, если в столбце числа (с числами могут быть любые знаки и слова, например руб. % и т.д.) как во втором столбце, то сортировка идет по числовому порядку, а не лексикографическому, если содержание смешанное как в третьем столбце, то сортировка идет для чисел по числовому по возрастанию, а для слов по алфавиту.
function sortTable(table, col, reverse) {
// изменяем tHead
let th = table.tHead;
[...th.rows].forEach(row => {
[...row.cells].forEach((cell, index) => {
cell.classList.remove("asc");
cell.classList.remove("desc");
if (index === col){
if(reverse) {
cell.classList.add("desc");
} else {
cell.classList.add("asc");
}
}
});
});
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
table {width: 100%;font: 12px arial; margin-top:30px}
th, td {min-width: 40px;text-align: center;}
th {font-weight: bold;}
thead th {cursor:pointer; font-size:14px; padding-bottom:10px}
<table>
<thead>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bork</td><td>1%</td><td>6-10</td>
</tr>
<tr>
<td>Yahoo</td><td>30%</td><td>А тут 30</td>
</tr>
<tr>
<td>Apple</td><td>5%</td><td>Здесь 100</td>
</tr>
<tr>
<td>Samsung</td><td>40%</td><td>50-60</td>
</tr>
</tbody>
</table>
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Думаю как-то так.
function sortTable(table, col, reverse) {
// изменяем tHead
let th = table.tHead;
[...th.rows].forEach(row => {
[...row.cells].forEach((cell, index) => {
cell.classList.remove("asc");
cell.classList.remove("desc");
if (index === col){
if(reverse) {
cell.classList.add("desc");
} else {
cell.classList.add("asc");
}
}
});
});
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
if (!isNaN(parseFloat(a.cells[col].textContent)) && !isNaN(parseFloat(b.cells[col].textContent))) {
let aVal = parseFloat(a.cells[col].textContent);
let bVal = parseFloat(b.cells[col].textContent);
return reverse * (aVal - bVal);
} else {
return reverse * (a.cells[col].textContent.trim() .localeCompare(b.cells[col].textContent.trim())
);
}
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
table {width: 100%;font: 12px arial; margin-top:30px}
th, td {min-width: 40px;text-align: center;}
th {font-weight: bold;}
thead th {cursor:pointer; font-size:14px; padding-bottom:10px}
<table>
<thead>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bork</td><td>1%</td><td>6-10</td>
</tr>
<tr>
<td>Yahoo</td><td>30%</td><td>А тут 30</td>
</tr>
<tr>
<td>Apple</td><td>5%</td><td>Здесь 100</td>
</tr>
<tr>
<td>Samsung</td><td>40%</td><td>50-60</td>
</tr>
</tbody>
</table>