I am trying to return an array of colors dependant on the number of values I have in a seperate array. For example I have an array of values [1, 5, 12, 23, 33, 76, 100, 354, 123], values.length = 9. My array of colors has 8 entries, therefore my array of colors should continue to loop until it reaches 9 entries. The below bar chart is what I want to achieve, the chart may have 100 entries therefor the colors would continue to loop until they reach 100 entries. The below works with the following code however this is returning 9*8 entries in the console.log as im looping over each value and pushing in the colors array. The result should be a single colors array of 9 entries. Appreciate any help.
const barColors = () => {
const colorsArr = [];
// const colorsArr = ['rgba(3, 4, 94, 1)', 'rgba(3, 4, 94, .8)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .2)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .8)'];
const values = [1, 5, 12, 23, 33, 76, 100, 354, 123];
values.forEach(() =>
colorsArr.push(
'rgba(3, 4, 94, 1)',
'rgba(3, 4, 94, .8)',
'rgba(3, 4, 94, .6)',
'rgba(3, 4, 94, .4)',
'rgba(3, 4, 94, .2)',
'rgba(3, 4, 94, .4)',
'rgba(3, 4, 94, .6)',
'rgba(3, 4, 94, .8)'
)
);
console.log(colorsArr);
return colorsArr;
};
If I understand well, you want the 9th element of values to get the first color again.
const colorsArr = ['rgba(3, 4, 94, 1)', 'rgba(3, 4, 94, .8)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .2)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .8)'];
const values = [1, 5, 12, 23, 33, 76, 100, 354, 123];
values.forEach((element, index) =>
$("#chart").append("<div><span>" + colorsArr[index % colorsArr.length] + "</span><div style='background-color: " + colorsArr[index % colorsArr.length] + "; width:" + element + "px; height:20px; margin:2px'></div></div>")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart"></div>
const barColors = () => {
const palette = ['rgba(3, 4, 94, 1)', 'rgba(3, 4, 94, .8)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .2)', 'rgba(3, 4, 94, .4)', 'rgba(3, 4, 94, .6)', 'rgba(3, 4, 94, .8)'];
const values = [1, 5, 12, 23, 33, 76, 100, 354, 123];
const colorsArr = []
for (let i = 0; i < values.length; i++) {
colorsArr.push(palette[i%palette.length])
}
console.log(colorsArr)
return colorsArr
}
The only part that may need explanation is palette[i%palette.length]. This is to avoid going over the length of palette. If the are more values than colors in palette, it will start from index 0 of palette to add do colors.