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.)
In jQuery the first argument of
each()is the index, not the element. You must use thethisorfunction (i, elem). Mootools has the element as the first parameter.– Sergio
Thanks for the touch, I fixed it :)
– Oralista de Sistemas
@Renan And what would the answer look like in this format "2 = 2, 6 = 1, 1 = 1" ??
– Alan PS
1 occurrence of each. If you want to count the individual numbers, you need to refine the logic further.
– Oralista de Sistemas
@Renan, can you give me an example of how to do ?
– Alan PS
@Alanps in your comment, you want to tell an occurrence of
2 = 2, or two occurrences of2? With more details we can help you better ;)– Oralista de Sistemas
@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!
– Alan PS