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

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>

O 2 appears twice, 6 once and 1 once ...

OBS: remembering that numbers change and are random ...

    
asked by anonymous 01.09.2014 / 23:13

4 answers

6

You can create HTML elements to save / view 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

    
02.09.2014 / 03:02
13

Just use a dictionary that has the values in the cells as keys;)

Type like this:

var dicionarioDeValores = {};

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

You will go through all the cells. Each time you enter a cell, if its value is already key to the dictionary, you increment. Otherwise, you start with 1. Good luck and happy coding!

    
01.09.2014 / 23:22
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>

Example Online: JsFiddle >

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

    
02.09.2014 / 02:44
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's the example JSFiddle.

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

    
02.09.2014 / 15:33