Chartjs-Chart JS โ€“ Change the color of the last element in a Bar Chart

2๐Ÿ‘

โœ…

Use a callback on the backgroundColor:

backgroundColor: this.data.map((item, index) => {
  if (index === this.data.length - 1) {
    return 'red';
  } else return 'blue'
})

Or using ternary operator:

backgroundColor: this.data.map((item, index) => {
  return index === this.data.length - 1 ? 'red' : 'blue'
}),

this.data is the data used for creating the chart.

Full solution:

data = [22, 19, 23, 84, 22];
labels: ["Red", "Blue", "Yellow", "Red", "Blue"],
  datasets: [{
    data: this.data,
    backgroundColor: this.data.map((item, index) => {
      return index === this.data.length - 1 ? 'red' : 'blue'
    }),
  }]
}

Leave a comment