Reputation: 1595
Is there a simple way to count the unique cells in a column (or row) in an HTML table with jQuery or plain Javascript?
Example: (table with only one column)
melon
banana
melon
strawberry
The counter would be 3.
Upvotes: 0
Views: 2707
Reputation: 16140
Try this:
var a = {}, l = 0;
$('table tr td:first-child').each(function(){
if (!a[$(this).text()]) {
l++;
a[$(this).text()] = true;
}
});
alert(l);
For HTML:
<table>
<tr><td>melon</td><td></td></tr>
<tr><td>banana</td><td></td></tr>
<tr><td>melon</td><td></td></tr>
<tr><td>strawberry</td><td></td></tr>
</table>
This will work for first column. If you want to count values in second column you would use selector table tr td:first-child+td
, for third table tr td:first-child+td+td
, etc.
Working example: http://jsfiddle.net/7K64j/1/
Upvotes: 3
Reputation: 66673
Try this:
var matches = [];
$('table td').each(function() {
if(!$.inArray($(this).text(), matches)==-1) matches.push($(this).text());
});
alert(matches.length);
Upvotes: 2