合并HTML表格中重复的数据行是常见的数据处理需求,以下是几种高效的方法:
function mergeDuplicateRows(tableId, columnIndex) {
const table = document.getElementById(tableId);
let previousValue = null;
let rowspan = 1;
for(let i = 1; i < table.rows.length; i++) { // 从第2行开始(跳过表头)
const currentValue = table.rows[i].cells[columnIndex].innerText;
if(currentValue === previousValue) {
table.rows[i].cells[columnIndex].style.display = "none";
rowspan++;
table.rows[i - rowspan + 1].cells[columnIndex].rowSpan = rowspan;
} else {
previousValue = currentValue;
rowspan = 1;
}
}
}
function mergeTableRows($array, $keyColumn) {
$result = [];
$previousValue = null;
$currentRowspan = 1;
foreach($array as $row) {
if($row[$keyColumn] === $previousValue) {
$currentRowspan++;
end($result)[$keyColumn.'_rowspan'] = $currentRowspan;
$row['_skip'] = true;
} else {
$previousValue = $row[$keyColumn];
$currentRowspan = 1;
}
$result[] = $row;
}
return $result;
}
/* 仅适用于相邻相同单元格视觉合并 */
td {
position: relative;
}
td:not(:empty) + td:not(:empty) {
margin-left: -1px; /* 视觉上合并边框 */
}
// Vue组件中
methods: {
mergeRows(data, key) {
return data.reduce((acc, curr) => {
const last = acc[acc.length - 1];
if (last && last[key] === curr[key]) {
last._span[key] = (last._span[key] || 1) + 1;
} else {
curr._span = { [key]: 1 };
acc.push(curr);
}
return acc;
}, []);
}
}
您需要针对哪种具体场景实现表格合并?我可以提供更具体的解决方案。