You can use each
tr and filter
to implement your requirement:
$("button").click(function(){
var group = [];
$("tr").each(function(index,item){
if(index > 0){
let id = $(item).find('td').eq(0).text();
let name = $(item).find('td').eq(1).text();
let count = parseInt($(item).find('td').eq(2).text());
let exist = group.filter(c=>c.name == name)[0];
if(exist != undefined){
exist.count += count;
}else{
group.push({id : id, name: name, count : count});
}
}
});
console.log(group);
});
Display result in table:
$.each(group, function(index,item){
$('#result tr:last').after('<tr>' + '<td>'+ item.id + '</td>' + '<td>'+ item.name + '</td>'+ '<td>'+ item.count + '</td>' + '</tr>');
});
$("button").click(function(){
var group = [];
$("#product tr").each(function(index,item){
if(index > 0){
let id = $(item).find('td').eq(0).text();
let name = $(item).find('td').eq(1).text();
let count = parseInt($(item).find('td').eq(2).text());
let exist = group.filter(c=>c.name == name)[0];
if(exist != undefined){
exist.count += count;
}else{
group.push({id : id, name: name, count : count});
}
}
});
$.each(group, function(index,item){
$('#result tr:last').after('<tr>' + '<td>'+ item.id + '</td>' + '<td>'+ item.name + '</td>'+ '<td>'+ item.count + '</td>' + '</tr>');
});
//console.log(group);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="product" border="1">
<tr><th>ID</th><th>Name of Goods</th><th>Qty</th></tr>
<tr><td>110</td><td>BOOK</td><td>2</td></tr>
<tr><td>111</td><td>Pencil</td><td>1</td></tr>
<tr><td>110</td><td>BOOK</td><td>3</td></tr>
<tr><td>112</td><td>Ruler</td><td>3</td></tr>
<tr><td>112</td><td>Ruler</td><td>1</td></tr>
</table>
<button click="sum()">Sum</button>
<table id="result" border="1">
<tbody>
<tr><th>ID</th><th>Name of Goods</th><th>Qty</th></tr>
</tbody>
</table>
2
solved how i can sum qty by grouping name of goods? [closed]