По сути, вашу проблему можно разделить на три более мелкие проблемы:
Получите данные таблицы HTML в объект javascript, который включает в себя массив объектов, каждый из которых имеет атрибут, который соответствует заголовку столбца и значению ячейки, так чтоВы можете отсортировать этот массив на основе значений атрибутов:
const jsonFromHtml = (tbody, thead) => {
let tableJson = {rows:[]};
[...tbody.children].forEach(tableRow => {
let rowEntry = {};
[...tableRow.children].forEach((cell, column) => rowEntry[thead.children[0].children[column].textContent] = cell.textContent);
tableJson.rows.push(rowEntry);
});
return tableJson;
};
Сортировать элементы строк в произвольном порядке:
const customSort = (arr, key, order) => {
let sortCompare = order == 'Desc' ? -1 : 1;
return arr.sort((first, second) => first[key]>second[key] ? sortCompare : first[key]<second[key] ? -sortCompare : 0);
};
Составьте внутреннее HTML тела таблицы на основе отсортированного массива строк:
const arrayToTable = (arr, tbody, thead) => {
let rows = [];
arr.forEach((row, rowNum) => {
row = [...thead.children[0].children].map(th => row[th.textContent] ? row[th.textContent] : '');
row = row.map(td => `<td>${td}</td>`);
row = `<tr>${row.join('')}</tr>`;
rows.push(row);
});
tbody.innerHTML = rows.join('');
};
const myTableTbody = document.querySelector('#myTable tbody');
const myTableThead = document.querySelector('#myTable thead');
const jsonFromHtml = (tbody, thead) => {
let tableJson = {rows:[]};
[...tbody.children].forEach(tableRow => {
let rowEntry = {};
[...tableRow.children].forEach((cell, column) => rowEntry[thead.children[0].children[column].textContent] = cell.textContent);
tableJson.rows.push(rowEntry);
});
return tableJson;
};
const customSort = (arr, key, order) => {
let sortCompare = order == 'Desc' ? -1 : 1;
return arr.sort((first, second) => first[key]>second[key] ? sortCompare : first[key]<second[key] ? -sortCompare : 0);
};
const arrayToTable = (arr, tbody, thead) => {
let rows = [];
arr.forEach((row, rowNum) => {
row = [...thead.children[0].children].map(th => row[th.textContent] ? row[th.textContent] : '');
row = row.map(td => `<td>${td}</td>`);
row = `<tr>${row.join('')}</tr>`;
rows.push(row);
});
tbody.innerHTML = rows.join('');
};
document.querySelector('#selectionOrder').addEventListener('change', function(){
let sortKey = this.value.match(/[a-z]+/)[0];
let sortOrder = this.value.match(/(A|De)sc/) ? this.value.match(/(A|De)sc/)[0] : 'Asc';
let myTableJson = jsonFromHtml(myTableTbody, myTableThead);
myTableJson.rows = customSort(myTableJson.rows, sortKey, sortOrder);
arrayToTable(myTableJson.rows, myTableTbody, myTableThead);
});
<label>Sort order:</label>
<select id="selectionOrder">
<option value="itemAsc">Item asc</option>
<option value="itemDesc">Item desc</option>
<option value="priceAsc">Price asc</option>
<option value="priceDesc">Price desc</option>
<option value="yearAsc">Year asc</option>
<option value="yearDesc">Year desc</option>
</select>
<table id="myTable">
<thead>
<tr>
<th>item</th>
<th>price</th>
<th>year</th>
</tr>
</thead>
<tbody>
<tr>
<td>Skoda Octavia</td>
<td>7000</td>
<td>2012</td>
</tr>
<tr>
<td>Toyota Yaris</td>
<td>3000</td>
<td>2011</td>
</tr>
<tr>
<td>Ford Focus</td>
<td>5000</td>
<td>2009</td>
</tr>
</tbody>
</table>