js按table某列的內(nèi)容進(jìn)行排序并該列內(nèi)容次數(shù)越少越排后
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
![]() ![]() function sortTableByColumn_count(myTable, columnIndex, isNumber) { const table = document.getElementById(myTable); var tbody = table.tBodies[0]; var rows = Array.from(tbody.rows); var firstRow = rows.shift(); tbody.deleteRow(0); // 移除原始的表頭 table.insertBefore(firstRow, tbody); // 將表頭重新添加到表格
rows.sort(function(a, b) { var cellA = a.cells[columnIndex]; var cellB = b.cells[columnIndex]; if (isNumber) { return parseFloat(cellA.textContent) - parseFloat(cellB.textContent); } else { return cellA.textContent.localeCompare(cellB.textContent); } });
// 計算每個數(shù)值出現(xiàn)的次數(shù) var counts = rows.reduce(function(counts, row) { var value = row.cells[columnIndex].textContent; counts[value] = (counts[value] || 0) + 1; return counts; }, {});
// 根據(jù)出現(xiàn)次數(shù)倒序排序 rows.sort(function(a, b) { return counts[b.cells[columnIndex].textContent] - counts[a.cells[columnIndex].textContent]; });
for(var i = 0; i < rows.length; i++) { tbody.appendChild(rows[i]); } } ? 該文章在 2024/12/6 9:33:49 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |