Coder_Nick Coder_Nick - 12 days ago 5
Javascript Question

Cycle through finite set of colours for indefinite set of data in Javascript

I'm using ChartJS to show stock data. I have seven colours I want to iterate through for the objects. When I add an 8th object, I want it's colour on the chart to be the first colour in the colour array.

$(document).ready(function () {
var context = document.getElementById('positions_chart');
var ctx = context.getContext("2d");

var quantities = [];
$("#positions_chart").data('positions').forEach(function(element){
quantities.push(element['quantity']);
});

var colors =[ "#FFCE56",
"#FFA75D",
"#46BFBF",
"#5975CB",
"#FF5D5D",
"#FFCC5D",
"#52DF52",
'black'
];

var tickers = [];
$("#positions_chart").data('positions').forEach(function(element){
tickers.push(element['ticker']);
});



var pieData = {
labels: tickers,
datasets: [
{
backgroundColor: [
"#FFCE56",
"#FFA75D",
"#46BFBF",
"#5975CB",
"#FF5D5D",
"#FFCC5D",
"#52DF52",
'black'

],
borderColor: "rgba(220,220,220,1)",
data: quantities
}
]
}

var chartInstance = new Chart(ctx, {
type: 'doughnut',
data: pieData,
options: {
responsive: true
}
});


The number of tickers indicate how many objects will need a colour on the chart. Cycling through the tickers to assign new colours is something ChartJS does in the background. The problem I'm facing is when tickers amount > colours amount I want the colours array to reset from the top. So I don't have blank colours for new objects in the chart.

Answer

You can switch out the colors array with a doubly-linked list.

Or just use an anonymous function on the object creation,

datasets: [{backgroundColor: (() => {
  let bgcolors = [];
  for (let i=0; i < tickers.length; ++i) bgcolors.push(colors[i % colors.length]);
  return bgcolors;
  })()
}]
Comments