How to retrieve the result of a table in a For Loop

0

I have a table in javascript, it is being structured by a for loop, but I need to calculate the result of it. It follows the code ..

for(i = 1; i<=30; i++) {
var maximo = 5;
var a = parseInt(Math.random()*maximo+1);
var b = parseInt(Math.random()*maximo+1);
var names = ["João", "Maria"];
var randomNames = (names[Math.random() < 0.5 ? 0 : 1]);

table += '<tr><td>'+i+'</td>';
table += '<td>'+ a +'</td>';
table += '<td>'+ b +'</td>';
table += '<td>'+ randomNames +'</td>';
table += '<td>'+ f1 +'</td>';
table += '<td>'+ f2 +'</td>';
table += '<td>'+ f3 +'</td></tr>';

}

table += '</tbody></table>';

In the fields f1, f2, f3, 2 different values will be displayed .. or it is Maça or Pera, the loop will go through 30 lines in the table at the end I need to know how many Pears and how many Pears appeared in Total, and I could not resolve this issue, thank you!

    
asked by anonymous 11.07.2017 / 20:02

1 answer

1

Hello, below is a possible solution:

fill an array with length = 30 of the words you want:

var names = ["João", "Maria"];
var array = [];
for(var i=0; i< 30; i++){
    array.push(names[Math.random() < 0.5 ? 0 : 1]);
}

fill in the table with the values of the array and then retrieve the number of times that repeat by:

// para a posição 0, no caso, João
array.reduce((a,e)=>{ return e==names[0] ? a=a+1 : a }, 0)

// para a posição 1, no caso, Maria
array.reduce((a,e)=>{ return e==names[1] ? a=a+1 : a }, 0)
    
11.07.2017 / 23:36