score:2

Accepted answer

given an array of number values named "data", you create a sorted array out of it. then you map the values of the original data, returning the appropriate color depending on its position in the sorted array.

const backgroundcolors = data.map(v => sorteddata.indexof(v) >= data.length - 3 ? 'red' : 'green');

please have a look at the runnable code sample below.

const labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o'];
const data = labels.map(l => math.floor(math.random() * 1000) + 1);
const sorteddata = data.slice().sort((a, b) => a - b);
const backgroundcolors = data.map(v => sorteddata.indexof(v) >= data.length - 3 ? 'red' : 'green');

new chart(document.getelementbyid('mychart'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "my dataset",
      data: data,
      backgroundcolor: backgroundcolors
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yaxes: [{
        ticks: {
          beginatzero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.3/chart.min.js"></script>
<canvas id="mychart" height="90"></canvas>


Related Query

More Query from same tag