0
votes

I have multiple arrays about different players stats that I'd like to append to a table, it's kinda working but the result is displaying the contrary of what I'd like: the table populates the data of each array horizontally instead of vertically like you normally would do for any table.

So how can I simply 'reverse' it to append vertically each data related to its column (and array)?

code part:

var ids = [0, 1, 2, 3]
var positions = [4, 9, 10, 6]
var levels = [1, 2, 1, 1]
var xps = [250, 500, 250, 750]
var attackings = [10, 18, 16, 14]
var defendings = [17, 10, 12, 16]
var shootings = [13, 15, 16, 14]
var dribblings = [11, 14, 18, 15]
var passings = [14, 15, 15, 17]
var headers = [18, 13, 15, 17]
var paces = [14, 17, 12, 13]
var endurances = [16, 11, 14, 15]
var physicals = [18, 15, 14, 16]

for (let row of [ids, positions, levels, xps, attackings, defendings, shootings, passings, dribblings, headers, paces, endurances, physicals]) {
  tableplayers.insertRow();
  for (let cell of row) {
    let newCell = tableplayers.rows[tableplayers.rows.length - 1].insertCell();
    newCell.textContent = cell;
  }
}
document.body.appendChild(tableplayers);
<table id="tableplayers" style="width:100%">
  <tr>
    <th>PLAYER ID #</th>
    <th>POSITION</th>
    <th>LEVEL</th>
    <th>XP</th>
    <th>ATTACKING</th>
    <th>DEFENDING</th>
    <th>SHOOTING</th>
    <th>PASSING</th>
    <th>DRIBBLING</th>
    <th>HEADER</th>
    <th>PACE</th>
    <th>ENDURANCE</th>
    <th>PHYSICAL</th>
    <th>SET / MODIFY STATS</th>
  </tr>
</table>
1

1 Answers

0
votes

You can easily achieve the result using reduce

var ids = [0, 1, 2, 3]
var positions = [4, 9, 10, 6]
var levels = [1, 2, 1, 1]
var xps = [250, 500, 250, 750]
var attackings = [10, 18, 16, 14]
var defendings = [17, 10, 12, 16]
var shootings = [13, 15, 16, 14]
var dribblings = [11, 14, 18, 15]
var passings = [14, 15, 15, 17]
var headers = [18, 13, 15, 17]
var paces = [14, 17, 12, 13]
var endurances = [16, 11, 14, 15]
var physicals = [18, 15, 14, 16]

const arr = [
  ids,
  positions,
  levels,
  xps,
  attackings,
  defendings,
  shootings,
  passings,
  dribblings,
  headers,
  paces,
  endurances,
  physicals,
];

const data = arr.reduce((acc, curr) => {
  curr.forEach((el, i) => {
    if (!acc[i]) acc[i] = [el];
    acc[i].push(el);
  })
  return acc;
}, []);


for (let row of data) {
  tableplayers.insertRow();
  for (let cell of row) {
    let newCell = tableplayers.rows[tableplayers.rows.length - 1].insertCell();
    newCell.textContent = cell;
  }
}


document.body.appendChild(tableplayers);
<table id="tableplayers" style="width:100%">
  <tr>
    <th>PLAYER ID #</th>
    <th>POSITION</th>
    <th>LEVEL</th>
    <th>XP</th>
    <th>ATTACKING</th>
    <th>DEFENDING</th>
    <th>SHOOTING</th>
    <th>PASSING</th>
    <th>DRIBBLING</th>
    <th>HEADER</th>
    <th>PACE</th>
    <th>ENDURANCE</th>
    <th>PHYSICAL</th>
    <th>SET / MODIFY STATS</th>
  </tr>
</table>