I would like to utilize a for loop to achieve the following task.
Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options.
If the number of values in the defined color set is less than the requested quantity, the loop should begin again from the first value once it reaches the last one.
Less critical but potentially useful is the ability to start fetching values at any index within the default values set and apply the same cycling condition as in option #1 – looping back to the beginning when reaching the end of the color array.
Here's some initial code along with sample data to illustrate my requirements.
var defaultColors = ["#90CAF9","#B39DDB","#7E57C2","#78909C","#AED581"] ;
var chartData = [12,24,30,40,15,23,35] ;
var dynamicColors = function (a) {
var colors = [];
for(i=0;i<a;i++){
colors.push(defaultColors[i]);
}
return colors;
}
And here is how the colors are being called
backgroundColor: dynamicColors(chartData.length),
In the above example, there are more data points than available color values, necessitating the loop to restart from the beginning of the color array.
Expected result for #1 - Looping through the array from the start.
["#90CAF9","#B39DDB","#7E57C2","#78909C","#AED581","#90CAF9","#B39DDB"]
Expected result for #2 - Starting from a specific index.
["#7E57C2","#78909C","#AED581","#90CAF9","#B39DDB","#7E57C2","#78909C"]