2

How can I count the distinct table rows by table column?

Example:

<table>
   <thead> 
      <tr>
        <th>NAME</th>
        <th>TECHNOLOGY</th>
     </tr>
   </thead>
   <tbody>  
     <tr>
        <td>john</td>
        <td>jQuery</td>
    </tr>
    <tr>
       <td>mark</td>
       <td>css</td>
    </tr>
    <tr>
       <td>blah</td>
       <td>css</td>
    </tr>
    <tr>
       <td>abc</td>
       <td>css</td>
    </tr>
    <tr>
       <td>xyz</td>
       <td>jQuery</td>
    </tr>
  </tbody>
</table>

I want Out put:

css : 3
jQuery : 2

here I don't know what technology is come in that cell but, I need to get the no of rows by the technology

Thanks in advance

1

3 Answers 3

7
var byTechnology = {};

$("table tbody td:nth-child(2)").each(function () {
    var tech = $.trim( $(this).text() );

    if ( !(byTechnology.hasOwnProperty(tech)) ) {
        byTechnology[tech] = 0;
    }

    byTechnology[tech]++;
});

console.log(byTechnology);
// {
//     css: 3,
//     jQuery: 2
// }
Sign up to request clarification or add additional context in comments.

Comments

1

Call function below on load. Check this jsFiddle out - http://jsfiddle.net/pqzKa/2/

function count()
{

var map = {};

$("tbody tr td:nth-child(2)").each(function(i, val){
              var key = $(val).text();
               if (key in map)                   
                   map[key]=map[key] + 1;                                    
               else
                   map[key] = 1;                           
              });

var result='';
for(var key in map)
{
 result += key + ':' + map[key] + '\n';   
}
alert(result);
}

The function builds a hashmap called map. It then iterates over the second cell of each tr in tbody and checks to see if it is present in the map. If not, it adds it to the hashmap with a count of 1. If yes, it increments the count by 1. I hope this helps.

Comments

1

Another route might be to write a more generic function for counting people who use certain technologies.

Assuming your using jQuery and your table has an id 'tech' you could do something like this

counter = function(textMatch){
    count=0;
    //loop through all <tr> s
    $('#tech').find('tbody tr').each(function( index ) {
        //if second <td> contains matching text update counter
        if($($(this).find('td')[1]).text() == textMatch){
            count++
        }
    });
    return count;
}

console.log('Number of people using CSS is ' + counter('css'));
console.log('Number of people using CSS is ' + counter('jQuery'));

//and so on

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.