const CHART = document.getElementById("chart");
Chart.defaults.global.animation.duration = 0;
Chart.plugins.register({
beforeUpdate: function(chart) {
// If this option is true, do the sorting. We only do this when the button is pressed
if (chart.options.sort) {
// This gets the dataArray for the first dataset
let dataArray = chart.data.datasets[0].data;
// We create an array of indexes
// [0, 1, 2 ... length - 1]
let dataIndexes = dataArray.map((d, i) => i);
// We sort these indexes by the data value
// If the data is [10, 0, 30, 20]
// dataIndexes starts as [0, 1, 2, 3]
// and is sorted into [1, 0, 3, 2]
dataIndexes.sort((a, b) => {
return dataArray[a] - dataArray[b];
});
// Npw we sort the data array so the chart will have the correct data
dataArray.sort((a, b) => a - b);
// At this point dataIndexes is sorted by value of the data,
// so we know how the indexes map to each other
// Now we need to sort the bar objects, labels and background colours
let meta = chart.getDatasetMeta(0);
let newMeta = [];
let labels = chart.data.labels;
let newLabels = [];
let newColors = [];
meta.data.forEach((bar, i) => {
// The meta.data array has the bars in the old order
// so we look up the new index by using the dataIndexes array.
// indexOf isn't the most efficient but we have a small number of bars
let newIndex = dataIndexes.indexOf(i);
// copy the bar to the correct location in the new array
newMeta[newIndex] = bar;
// Copy the label to the new position
newLabels[newIndex] = chart.data.labels[i];
// Copy the color to the new position
newColors[newIndex] = chart.data.datasets[0].backgroundColor[i];
});
// update the chart
meta.data = newMeta;
chart.data.labels = newLabels;
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.