[Chartjs]-Sort a Chart from Lowest to Highest Value in Chart JS

1👍

Here is the update:

if (chart.options.sort) {
      let labels = chart.data.labels;
      let dataArray = chart.data.datasets[0].data.slice();
      let mapValueLabel = {};
      dataArray.forEach((value, index) => {
        mapValueLabel[value] = labels[index];
      });
      // sort data array as well
      dataArray.sort((a, b) => b - a);
      let meta = chart.getDatasetMeta(0);
      let newLabels = [];
      dataArray.forEach((a, i) => {
        newLabels[i] = mapValueLabel[a];
      });
      chart.data.datasets[0].data = dataArray;
      chart.data.labels = newLabels;
        }
      }

Demo:
https://jsfiddle.net/woL9ynpv/

My change is simple.
I create the map to save value and label:

map{value:label}

After sorting value, we iterate the new list data array and assign label base on the value key.

Leave a comment