score:5

Accepted answer

There is no built-in way to create your chart using an array straight into the data.

But you can create a small work around using Chart.js plugins. They let you handle events triggered during the whole creation of the chart, such as before it is initialized, after a resize, etc.


Follows a small plugin that will populate all the data for you using an array :

var myPlugin = {
    // We edit what is happening before the chart is initialized.
    beforeInit: function(chart) {
        var data = chart.config.data;

        // `APIarray` is what you get from your API.
        // For every data in this array ...
        for (var i = 0; i < APIarray.length; i++) {
            // Populate the labels array with the first value ..
            data.labels.push(APIarray[i][0]);
            // .. and the data with the second value
            data.datasets[0].data.push(APIarray[i][1]);
        }
    }
};

Then you need to add this newly created plugin to your Chart plugin services :

Chart.pluginService.register(myPlugin);


Make sure to register the plugin before creating the chart (before calling new Chart()), or else it won't work.
I also suggest to have an empty data in your chart (before the plugin occurs) to make sure you won't have data you don't want.

You can see a fully working example on this jsFiddle.


Related Query

More Query from same tag