user10063483
user10063483

Reputation:

Sorting the Bars in Chart.JS Bar Graph

I have been recently experimenting with ChartJS and have come into a problem regarding sorting the bars in descending order, from lowest to highest. I have tried to debug but found no luck.

Upvotes: 2

Views: 8206

Answers (1)

Ballsigno
Ballsigno

Reputation: 501

Are you sure the "beforeupdate" is called when you click the "Sort Data" button, because it seems you use the wrong variable.

barChart → barGraph

UPDATED The old one link
UPDATED Here is the link

// Get the data from each datasets.
var dataArray = [];
$.each(chart.data.datasets, function() {
    dataArray.push(this.data);
});
// Get the index after sorted.
let dataIndexes = dataArray.map((d, i) => i);
dataIndexes.sort((a, b) => {
    return dataArray[a] - dataArray[b];
});
// create after sorted datasets.
var tempDatasets = [];
$.each(dataIndexes, function() {
    tempDatasets.push(chart.data.datasets[this]);
});
// apply it
chart.data.datasets = tempDatasets;

What data is returned using Ajax?

data = [{
    sample : "ALPINE",
    electric : 100,
    mpg: 200,
    urban: 300,
    vmt: 400,
    airtravel: 500,
    renewable: 100,
    conservation : 200,
    heating: 300,
    water: 400,
    cefficiency: 500,
    shiftc: 100,
    healthyd: 200
}];

Upvotes: 1

Related Questions