Chartjs-Merge data into one bar, for similar hours in ChartJS

1👍

You can reduce your data using Array.reduce as follows.

const reducedData = data.reduce((acc, curr) => {
  curr.x = curr.x.substring(0, 13);
  const retained = acc.find(o => o.x == curr.x);
  if (retained) {
    retained.y += curr.y;
  } else {
    acc.push(curr);
  }
  return acc;
}, []);

Please take a look at your amended and runnable code below and see how it works.

const data = [
  {x: '2022-10-03T07:43:00', y: 1},
  {x: '2022-10-03T07:50:00', y: 1},
  {x: '2022-10-03T08:30:00', y: 1},
  {x: '2022-10-03T08:10:00', y: 1},
  {x: '2022-10-03T09:15:30', y: 1},
  {x: '2022-10-03T09:30:00', y: 1},
  {x: '2022-10-03T10:05:00', y: 1},
  {x: '2022-10-03T10:10:00', y: 1},
  {x: '2022-10-03T10:45:00', y: 1},
  {x: '2022-10-03T15:15:00', y: 1},
];

const reducedData = data.reduce((acc, curr) => {
  curr.x = curr.x.substring(0, 13);
  const retained = acc.find(o => o.x == curr.x);
  if (retained) {
    retained.y += curr.y;
  } else {
    acc.push(curr);
  }
  return acc;
}, []);
        
new Chart('peh-bar-chart', {
    type: 'bar',
    data: {
      datasets: [{
        label: '# of Votes',
        data: reducedData,
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        x: {
          type: 'time',
          time: {
            unit: 'hour',
            tooltipFormat: 'd MMM yyyy hA' 
          }
       }
     }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.0/chartjs-adapter-moment.min.js"></script>
<canvas id="peh-bar-chart" height="100"></canvas>

Leave a comment