[Chartjs]-How can I sort data from highest to lowest in chart.js

15👍

Here is how you can merge and sort data and labels together.
first sort them then assign newArrayData to data property and newArrayLabel to labels property of your config object.

arrayLabel = ["Total", "301 Redirect", "Broken Pages (4xx Errors)", "Uncategorised HTTP Response Codes", "5xx Errors", "Unauthorised Pages", "Non-301 Redirects"]

arrayData = [16, 1, 14, 0, 0, 0, 1];

arrayOfObj = arrayLabel.map(function(d, i) {
  return {
    label: d,
    data: arrayData[i] || 0
  };
});

sortedArrayOfObj = arrayOfObj.sort(function(a, b) {
  return b.data>a.data;
});

newArrayLabel = [];
newArrayData = [];
sortedArrayOfObj.forEach(function(d){
  newArrayLabel.push(d.label);
  newArrayData.push(d.data);
});

console.log(newArrayLabel);
console.log(newArrayData);

Leave a comment