I have a Javascript array of 20 RGB color values that looks like this:
defaultColors: [ rgb(58, 185, 180)','rgb(63, 186, 172)','rgb(71, 185, 159)','rgb(80, 185, 146)','rgb(90, 186, 132)','rgb(103, 187, 119)','rgb(117, 188, 104)','rgb(137, 193, 96)','rgb(163, 200, 90)','rgb(189, 206, 87)','rgb(212, 214, 86)','rgb(232, 219, 87)','rgb(245, 221, 89)','rgb(254, 221, 87)','rgb(254, 216, 83)','rgb(254, 206, 78)', 'rgb(253, 193, 72)','rgb(251, 178, 66)','rgb(244, 163, 63)','rgb(240, 150, 60)']
At any given time I may only need, say, 7 of these colors, but I want to pull colors from the full spectrum. I don't just want the first 7 colors. I'd need something more like this:
Or say I need 10 colors. That would look more like this:
Suggestions around how to pull this off?
When you need 7, evenly spaced, Math.ceil(20/7) = 3, so you can do:
var chosenColors = [];
for(var i =0; i<20 && chosenColors.length<7; i+=3) chosenColors.push(defaultColors[i]);
When you need 10, evenly spaced, Math.ceil(20/10) = 2, so you can do:
var chosenColors = [];
for(var i =0; i<20 && chosenColors.length<10; i+=2) chosenColors.push(defaultColors[i]);
// pick n elements from a, distibuted evenly
pickn = function(a, n) {
var p = Math.floor(a.length / n)
return a.slice(0, p * n).filter(function(_, i) {
return 0 == i % p
})
}
// test
test = [0,11,22,33,44,55,66,77,88,99,111,222,333,444,555,666,777,888,999]
for (i = 1; i < test.length; i++)
console.log(i, pickn(test, i))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With