1👍
Here’s how you do it with a separate function. Adapted from How can I sort, insert in between and update full dataset in chartjs?
var MyBarChartMethods = {
// sort a dataset
sortByLabel: function (chart) {
// get data from chart elements (instead of messing up the actual data object)
var data = []
chart.datasets.forEach(function (dataset, i) {
dataset.bars.forEach(function (bar, j) {
if (i === 0) {
data.push({
label: parseFloat(chart.scale.xLabels[j]),
values: [bar.value]
})
} else
data[j].values.push(bar.value)
});
})
// sort the data based on label
data.sort(function (a, b) {
if (a.label > b.label)
return 1;
else if (a.label < b.label)
return -1;
else
return 0;
})
// update the chart elements using the sorted data
chart.datasets.forEach(function (dataset, i) {
dataset.bars.forEach(function (bar, j) {
if (i === 0)
chart.scale.xLabels[j] = data[j].label;
bar.label = data[j].label;
bar.value = data[j].values[i];
})
});
chart.update();
},
}
and you call it thus
MyBarChartMethods.sortByLabel(myBarChart)
Fiddle – http://jsfiddle.net/jk1k0g5u/
Source:stackexchange.com