Count the number of occurences in a table with jquery

I have an html table and I’m wondering if there is a way that I could find the number of occurrences of a given number and display them on the page with jquery?

Occurence of 4: 1
Occurence of 11: 2
.
.
. etc…

 <table id='tab' width="35%" border="1">
      <tr>
        <td>3</td>
        <td>4</td>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>11</td>
        <td>8</td>
        <td>7</td>
      </tr>
      <tr>
        <td>6</td>
        <td>6</td>
        <td>11</td>
        <td>7</td>
      </tr>
      <tr>
        <td>5</td>
        <td>4</td>
        <td>20</td>
        <td>7</td>
      </tr>
    </table>

Use :contains() selector and length property:

$('table td:contains(4)').length // => Occurence of 4
$('table td:contains(11)').length // => Occurence of 11

I made an example for you: http://jsfiddle.net/1d7o8p5k/
That code finds occurencies count for each number in given table

that was fast!! thanks alot @megazoid.

There is one issue with this code. It counts all 1s, 2s, 3s etc…seperately. In the example, there is only one “1” but it counts 3 because there is an “11”. How can we change this? thanks.

Fixed: http://jsfiddle.net/1k6usych/1/

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.