Chartjs-Chart.js sum of the last 3h datavalues in a line chart

1πŸ‘

βœ…

I don’t know am I fully understand what you are asking about. But if you have an array (datapoints) and you need to take some amount of last elements, you can use arr.slice(-3).

Check this example with chart.js:

let ctx = document.getElementById("myChart").getContext('2d');
let myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        datasets: [{
            label: 'datapoints',
            backgroundColor: 'rgba(0, 0, 0, 0)',
            borderColor: 'rgba(255, 99, 132, 1)',
            data: [12, 19, 3, 15, 2, 3, 7, 10, 5, 8],
            borderWidth: 2
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

let nLastElements = 3;
let sum = myChart.data.datasets[0]
          .data
          .slice(-nLastElements)
          .reduce((a, b) => a + b, 0);

console.log("Sum of last " + nLastElements + " elements: " + sum);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Leave a comment