Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an evenly "spaced" number of indexes from a large array.

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:

enter image description here

Or say I need 10 colors. That would look more like this:

enter image description here

Suggestions around how to pull this off?

like image 901
Brandon Durham Avatar asked Feb 20 '12 17:02

Brandon Durham


2 Answers

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]);
like image 101
Diego Avatar answered Nov 14 '22 22:11

Diego


// 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))
like image 45
georg Avatar answered Nov 14 '22 23:11

georg