Search code examples
javascriptjqueryhtml-tableuniquecells

Count unique cells in a column or row of an HTML table with Javascript/jQuery


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.


Solution

  • 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/