How to count how many times a value appears in a table

Asked

Viewed 2,358 times

9

How to count how many times a value appears in a table ?

Example:

<table id="table">
  <tr>
    <td> 2 </td>
  </tr>
  <tr>
    <td> 6 </td>
  </tr>
  <tr>
    <td> 2 </td>
  </tr>
  <tr>
    <td> 1 </td>
  </tr>
</table>

The 2 appears twice, the 6 once and the 1 once...

Note: remembering that the numbers change and are random...

4 answers

13

Just use a dictionary keyed values in cells ;)

Kind of:

var dicionarioDeValores = {};

$("#table")
        .find("td")
        .each(function (index, elem) {
    var valor = $(elem).text();
    if (!dicionarioDeValores[valor]) {
        dicionarioDeValores[valor] = 1;
    } else {
        dicionarioDeValores[valor]++;
    }
});

You will scroll through all cells. Each time you enter a cell, if its value is already a dictionary key, you increment it. Otherwise, you initialize with 1. Good Luck and happy coding!

  • 1

    In jQuery the first argument of each() is the index, not the element. You must use the this or function (i, elem). Mootools has the element as the first parameter.

  • 1

    Thanks for the touch, I fixed it :)

  • @Renan And what would the answer look like in this format "2 = 2, 6 = 1, 1 = 1" ??

  • 1 occurrence of each. If you want to count the individual numbers, you need to refine the logic further.

  • @Renan, can you give me an example of how to do ?

  • @Alanps in your comment, you want to tell an occurrence of 2 = 2, or two occurrences of 2? With more details we can help you better ;)

  • @Renan, I already managed to solve the problem, I used your example from above and put the result in an array using a FOR!!! Thanks!

Show 2 more comments

6


You can create HTML elements to go saving/displaying the count:

$('#table td').each(function (i, e) {
    if ($('[data-numero=' + $(this).text() + ']').length) {
        var numero = $('[data-numero=' + $(this).text() + ']').children('span');
        numero.text( parseInt(numero.text()) + 1 );
    } else {
        $('body').append('<div data-numero="' + $(this).text() + '">Número ' + $(this).text() + ': <span>1</span></div>');
    }
});

see working on Jsfiddle

2

I decided to do it in pure Javascript, just to have one more search option:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tabela</title>
<script type="text/javascript">                
        Calcular = function(id){
            var table = document.getElementById(id);
            var td    = table.getElementsByTagName('td');
            var dados = {};
            for(i = 0; i < td.length; i++)
            {
                dados[td[i].innerHTML] = (dados[td[i].innerHTML] === undefined)? 1: (dados[td[i].innerHTML] + 1);                
            }
            console.log(dados);
        }
</script>
</head>
<body>
    <table id="table">
      <tr>
        <td>2</td>
      </tr>
      <tr>
        <td>6</td>
      </tr>
      <tr>
        <td>2</td>
      </tr>
      <tr>
        <td>1</td>
      </tr>
      <tr>
        <td>1</td>
      </tr>
      <tr>
        <td>1</td>
      </tr>
    </table>
    <button type="button" onclick="Calcular('table')">Calcular</button>
</body>
</html>

Online Example: Jsfiddle

Note: in my example there is more td and therefore changes the numbering.

1

This is a case where you can benefit from associative arrays.

//Array associativo
var histograma = {};

// A função abaixo é chamada para cada célula:
$('table#table tr td').each(function() {
    var chave = $(this).text();       // A chave do histograma
    var val = histograma[chave] || 0; //Caso o valor não exista, assuma zero
    histograma[chave] = val + 1;      //Contagem de ocorrências
});

// Listando o resultado do método acima:
for (var chave in histograma) {
    $('#res').append(chave + ':' + histograma[chave] + '<br/>'); 
}

The result of this snippet is as follows::

Tabela:
2
6
2
1
Ocorrências:
2 :2
6 :1
1 :1

Here is the example Jsfiddle.

(Edit - after reading the other answers, this is basically a slightly leaner version of Renan.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.