How to Recover Result from a Table in a Loop For

Asked

Viewed 76 times

0

Personal I have a table in javascript, it is being structured by a loop for, however I need to calculate the result of 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 F1, F2, F3 fields, 2 different values will be displayed.. Either it’s Mace or Pera, the loop will go through 30 lines in the table at the end I need to know how many Apples and Pears appeared in Total, I broke my nut here and I couldn’t solve that question, I thank you!

1 answer

1

hello, below 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 the table with the array values and then recover the amount of times they repeat for:

// 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)

Browser other questions tagged

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