Home > OS >  Assign colors in specific order in array
Assign colors in specific order in array

Time:10-23

I want to loop array and assign colors in specific order to each array element.

First, fifty, ninth and so on should have red color.

Second, sixth, tenth and so on should have green color.

Third,Seventh, eleventh and so on should have blue color.

Fourth, eighth, twelfth so on should have yellow color.

Link to Fiddle Playground

const colors = ['red', 'green', 'blue', 'yellow'];
const arr = [1, 'a', 3, 'b', 55, 69, 71, 8, 91, 10];
let color;

arr.forEach((el, i) => {
  switch (i) {
    case i % 1:
      color = 'red';
      break;
    case i % 2:
      color = 'green';
      break;
    case i % 3:
      color = 'blue';
      break;
    case i % 4:
      color = 'yellow';
      break;

    default:
      color = 'red';
      break;
  }

  console.log('color:', el, i, color);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can probably avoid the switch like this:

const colors = ["red", "green", "blue", "yellow"];
const arr = [1, "a", 3, "b", 55, 69, 71, 8, 91, 10];
let color;

arr.forEach((el, i) => {
  color = colors[i % colors.length];
  console.log("color:", el, i, color);
});

i % colors.length gives you the color index

Tip: you can add more colors to your array and it will still work

CodePudding user response:

You need to make a couple changes. switch(i) should be switch ((i 1) % 4) , so that you switch on the evaluated expression of index 1 mod 4 (plus 1 so that you don't mod' on 0, which is the first index and so that you get usable results). Also, your cases should be case 1:, case 2:, etc.. Take a look below:

const colors = ['red', 'green', 'blue', 'yellow'];
const arr = [1, 'a', 3, 'b', 55, 69, 71, 8, 91, 10];
let color;

arr.forEach((el, i) => {
  switch ((i   1) % 4) {
    case 1:
      color = 'red';
      break;
    case 2:
      color = 'green';
      break;
    case 3:
      color = 'blue';
      break;
    case 0:
      color = 'yellow';
      break;

    default:
      color = 'red';
      break;
  }

  console.log('color:', el, i, color);
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related