0

I have successfully displayed the value, but why is only one value displayed? I want the value in sequence

This my code

/*my datasets code*/
datasets: [{
  label: 'Daily Data',
  data: [730000, 1012000, 1220000, 1831000, 560000, 2012000, 890000],
  borderColor: '#3f89fb',
  borderWidth: 3,
  fill: false
}]

/*my tooltips code*/
tooltips: {
  callbacks: {
    label: function(tooltipItem, chart) {
      for (var i = 0; i < chart.datasets[0].data.length; i++) {
        return chart.datasets[0].data[i] / 1e6 + 'M';
      }
    }
  }
}

and this my result, all day value is 0.73M enter image description here

Firmansyah
  • 106
  • 12
  • 27

3 Answers3

2

Look in the Tooltip Item Documentation.

In your case tooltipItem.index contains the index of this data item in the dataset. So you can return the value doing so:

function(tooltipItem, chart) {
    return chart.datasets[0].data[tooltipItem.index] / 1e6 + 'M';
}

And here is the demo:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Daily Data',
            data: [730000, 1012000, 1220000, 1831000, 560000, 2012000, 890000],
            borderColor: '#3f89fb',
            borderWidth: 3,
            fill: false
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        tooltips: {
            callbacks: {
                label: function(tooltipItem, chart) {
                    return chart.datasets[0].data[tooltipItem.index] / 1e6 + 'M';
                }
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Towkir
  • 3,889
  • 2
  • 22
  • 41
Marcel T.
  • 126
  • 7
0

This is because return stops execution and exits the function. return always exits its function immediately, with no further execution if it's inside a loop.

See this answer: Does return stop a loop?

C. Molendijk
  • 2,614
  • 3
  • 26
  • 35
0

Instead of return inside for loop which will exit the loop, you can save your results somewhere like below

var result = []
for (var i = 0; i < chart.datasets[0].data.length; i++) {
        result.push(chart.datasets[0].data[i] / 1e6 + 'M');
      }
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22