0

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.

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

3 Comments

+1 This method is more efficient than the one i posted as it uses array indices for matching and thus eliminates the need for array traversal.
@TimDown I didn't realize that. I've switched to $(this).text().
The link mentioned above is helpful
2

Try this:

var matches = [];
$('table td').each(function() {
  if(!$.inArray($(this).text(), matches)==-1) matches.push($(this).text());
});
alert(matches.length);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.