How to add same results in one column โ€“ Chart.js

1๐Ÿ‘

โœ…

You should put the values of xNav are 1 to 5. Then define data as an Object to store each count of values from xNav, then iterate it based on inputVal array to get each count.

let inputNav = document.getElementsByClassName('inputNav');
let xNav = [1,2,3,4,5];
let data = {};
let barColors = ['green','red','orange','yellow']; // define this at the number of colors you want

xNav.forEach((x) => { data[x] = 0; });
for (let i = 0; i < inputNav.length; i++) {
  inputValNav = inputNav[i].innerHTML;
  if(inputValNav !== '') {
    data[inputValNav]++;
  }
}
let yNav = Object.values(data);

const ctx = document.getElementById('chartnavigation').getContext('2d');

new Chart(ctx, {
    type: "bar",
    data: {
      labels: xNav,
      datasets: [{
        label: 'data',
        backgroundColor: barColors,
        barPercentage: 0.5,
        data: yNav
      }]
    },
    options: {
      legend: {display: false},
      title: {
        display: true,
        text: "Title"
      },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<div>Data :</div>
<table border="1">
  <tr>
    <td>
      <div class="inputNav">2</div>
    </td>
    <td>
      <div class="inputNav">3</div>
    </td>
    <td>
      <div class="inputNav">4</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">4</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
    <td>
      <div class="inputNav">5</div>
    </td>
  </tr>
</table>

<canvas id="chartnavigation"></canvas>

Leave a comment