我用html table
画图。我想组合2个以上的duplicate rows
并求和重复行中的值。
我的表表示例:
名称金额
约翰200
约翰300
约翰100
harish 400
harish 400
预期结果:
名称金额
约翰600
harish 800
我尝试使用下面的jQuery代码,但它只是合并两个重复的行,如果出现两个以上的重复行,则不是合并,而是在增加价值并显示重复的行。
HTML代码:
<table>
<tr>
<td>Name</td>
<td>quantity</td>
<td>expired</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">B</td>
<td class="val">100</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">C</td>
<td class="val">35</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">C</td>
<td class="val">35</td>
<td class="date">date</td>
</tr>
</table>
jQuery代码:
var first_row = '<tr class="row"><td class="id">NULL</td></tr>';
var rowCount = 0;
var rowSum = 0;
$.each($('.row'), function (index, curRow) {
if ($(first_row).find('.id').text() != $(curRow).find('.id').text()) {
if (rowCount > 1) {
$(first_row).find('.val').text(rowSum);
$(first_row).find('.val').css('background-color','silver');
for (i = 0; i < rowCount; i++) {
$(first_row).next('.row').find('.val').remove();
$(first_row).next('.row').find('.date').remove();
$(first_row).next('.row').find('.id').remove();
}
}
first_row = $(curRow);
rowSum = 0;
rowCount = 0;
}
rowSum += parseInt($(curRow).find('.val').text());
rowCount += 1;
});
if (rowCount > 1) {
$(first_row).find('.val').text(rowSum);
$(first_row).find('.val').css('background-color','silver');
for (i = 0; i < rowCount; i++) {
$(first_row).next('.row').find('.val').remove();
$(first_row).next('.row').find('.date').remove();
$(first_row).next('.row').find('.id').remove();
}
}
结果:
名称已过期
一个100的日期
A 25日期
A 25日期
B 100日期
C 70日期
在这里,我要在“名称”列中所有记录应为
distinct
并求和。请在这件事上给予我帮助
最佳答案
使用jQuery .nextAll()和.filter()的另一种方法
$('.row').each(function() {
var thisId = $(this).find('.id').text();
var sumVal = parseFloat($(this).find('.val').text());
var $rowsToGroup = $(this).nextAll('tr').filter(function() {
return $(this).find('.id').text() === thisId;
});
$rowsToGroup.each(function() {
sumVal += parseFloat($(this).find('.val').text());
$(this).remove();
});
$(this).find('.val').text(sumVal);
});