Reputation: 1823
I've a table generated from an external DB. Using the below line I generate the rows of the table:
var row = $("<div id='row' class='divTableRow'><div class='divTableCell'>"+(i+1)+"</div><div class='divTableCell'>"+fullName+"</div><div class='divTableCell'>"+username+"</div><div class='divTableCell'>"+resName+"</div><div class='divTableCell'>"+finalRating+"</div><div class='divTableCell'>"+date+"</div></div>");
$(".divTable").append(row);
In the table a have a column called username
which is basically a unique value to its user.
What I willing to do is to create a column, called for example count
which should should the number of occurrences of the value username
Example:
+----+------------+---------------+--------+-------+
| No | Full Name | username | Outlet | Count |
+----+------------+---------------+--------+-------+
| 1 | Stacy Gar | 0649039233 | Out2 | 2 |
+----+------------+---------------+--------+-------+
| 2 | Jeremy Fa | 0349959522 | Out5 | 1 |
+----+------------+---------------+--------+-------+
| 3 | Stacy Gar | 0649039233 | Out1 | 2 |
+----+------------+---------------+--------+-------+
As you can see above in the table the username
0649039233
has bought from Out1
and Out2
that's why it has in the count column 2
Any ideas on how I can achieve similar results in using jQuery or Javascript?
Upvotes: 1
Views: 62
Reputation: 3435
When you are creating the row you can save the userName and its occurrence number in this format:
userName1:2;userName2:1;userName3:1;
':' separate the userName and it's occurrence and ';'separate records.
Before all things you must have two array.
var occurrence =[];
var userNames = [];
and when creating each row:
var index = userNames.indexOf(userName);
if(index > 0) // the user name is repeated. we only increase occurrence
{
occurrence[index] = occurrence[index] + 1;
}
else
{
userNames.push(userName);
occurrence.push[1];
}
Now you have what you want:
occurrence of UserNames[i] = occurrence[i];
And you can use like this:
for(i=0;i<$('#yourTable').children('tr').length;i++) //or length-1 if you have header row
{
row = $('#yourTable').children('tr').eq(i); // or eq(i+1) if you have header row
row.children('td').eq(2).html(userNames[i]));
row.children('td').eq(4).html(occurrence[i]));
}
Upvotes: 0
Reputation: 35670
For each row, grab the user ID, then use filter() on the entire table to count the number of its occurrences:
$('tr').each(function() {
var userID = $(this).find('td:nth-child(3)').text(),
count;
count = $('td:nth-child(3)').filter(function() {
return $(this).text() === userID;
}).length;
$(this).find('td:last').text(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><th>No<th>Full Name <th>username <th>Outlet <th>Count
<tr><td>1 <td>Stacy Gar <td>0649039233 <td>Out <td>
<tr><td>2 <td>Jeremy Fa <td>0349959522 <td>Out <td>
<tr><td>3 <td>Stacy Gar <td>0649039233 <td>Out <td>
</table>
Upvotes: 2