How can I sort the stacked bar charts in Highcharts by the sum of positive response?

540 Views Asked by At

Can someone look at my bar chart and let me know how can I sort the stacks by the total positive response rate (sum of the top two green categories that are above 0%)?

https://jsfiddle.net/samwhite/tqLya8h1/1/

    let selection = departments.forEach((dat, d) => {
      data[dat]["104"].forEach((val, i) => {
        if (i<2) {
          options[i].data.push(val);
        } else {
          options[i].data.push(-val);
        }
      })
    });
    
    let chart = Highcharts.chart('container', {
      chart: {
        type: 'column',
      },
      series: options
    });
2

There are 2 best solutions below

1
Sebastian Wędzel On BEST ANSWER

You can sort the departments in ascending order and later create new data by the result.

departments.sort((a, b) => {
    return ((data[a]["104"][0] + data[a]["104"][1]) - (data[b]["104"][0] + data[b]["104"][1]))
})

Demo: https://jsfiddle.net/BlackLabel/cdun0mx3/

0
Fakt309 On

for sort any array you can use this function sort

function sort(arr, dir) {
  for (var i = 0; i < arr.length-1; i++) {
    for (var j = 0; j < arr.length-i-1; j++) {
      if ((arr[j+1] > arr[j] && dir == "desc") || (arr[j+1] < arr[j] && dir == "asc")) {
        var tmp = arr[j+1];
        arr[j+1] = arr[j];
        arr[j] = tmp;
      }
    }
  }
}

var testArr = [6, 34, 22, 12, 3, 3, 4];

sort(testArr, "asc");
console.log(testArr);

sort(testArr, "desc");
console.log(testArr);