0

I have a series of values in a table and I would like to separate them 3 by 3 to use them as an RGB value.

I've tried something like this:

var color = [143,204,211,25,35,59,204,219,209,128,135,124,38,139,216,84,106,105,205,87,114,165,175,88];
var cList = $('ul.color_palette');
            $.each(color, function(i)
            {
                var li = $('<li/>')
                    .addClass('color'+ i)
                    .css('background-color', 'rgb(' + color[i] + ')')
                    .appendTo(cList);            
            });

I'd like it to look something like this:

<ul class="color_palette">
   <li class="color0" style="background-color: rgb(143, 204, 211);"></li>
   <li class="color1" style="background-color: rgb(25, 35, 59);"></li>
   <li class="color2" style="background-color: rgb(204, 219, 209);"></li>
   <li class="color3" style="background-color: rgb(128, 135, 124);"></li>
   <li class="color4" style="background-color: rgb(38, 139, 216);"></li>
   <li class="color5" style="background-color: rgb(84, 106, 105);"></li>
   <li class="color6" style="background-color: rgb(205, 87, 114);"></li>
   <li class="color7" style="background-color: rgb(165, 174, 88);"></li>
</ul>

Can you help me?

Creatz
  • 49
  • 5

1 Answers1

0

This is really just a chunking exercise on the color array to make clusters of three values - which can then be used in the iteration in your existing code.

Solution modified from this answer to a different question (https://stackoverflow.com/a/8495740/5867572 - @Blazemonger)

var color = [143,204,211,25,35,59,204,219,209,128,135,124,38,139,216,84,106,105,205,87,114,165,175,88];
var rgbValues = [];

for (i = 0; i < color.length; i += 3) {
  rgbValues.push(color.slice(i, i + 3).join(', '));
}
console.log(rgbValues); 
// gives [
//  "143, 204, 211",
//  "25, 35, 59",
//  "204, 219, 209",
//  "128, 135, 124",
//  "38, 139, 216",
//  "84, 106, 105",
//  "205, 87, 114",
//  "165, 175, 88"
//]
gavgrif
  • 15,194
  • 2
  • 25
  • 27