简体   繁体   中英

Assign colors in specific order in array

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); });

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

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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM