Home > Mobile >  Is there a way to match 3 colors, alternating, to odd numbers
Is there a way to match 3 colors, alternating, to odd numbers

Time:05-31

I am trying to create a list of 3 phase color coding.

ex :

Red: 1.
Black: 3.
Blue: 5.
Red: 7.
and so on and so fourth, until 100.

Same thing on the even side of numbers.

Red: 2
Black: 4
Blue: 6
Red: 8.

How would I achieve this in JavaScript?

PS : I am new to coding and have never used stackoverflow yet so apologies.

CodePudding user response:

My solution to that is to create an array of colors, then just check if even or odd, then use the modulo to identify the iterating colors from start to end.

var arr = []
var even_colors = ["Red", "Black", "Blue"];
var odd_colors = ["Yellow", "Pink", "Orange"]
var index = 0;
var even_counter = 0;
var odd_counter = 0;

for(var i = 1; i <= 100; i  ){
  if( i % 2 == 0 ){
    // You can perform any action here like DOM manipulation if you can
    arr.push(even_colors[even_counter % 3]);
    even_counter  ;
  }else{
    arr.push(odd_colors[odd_counter % 3]);
    odd_counter  ;
  }
}

// Or make use of the color array here

CodePudding user response:

You can create an array of desired length using Array.from and then fill the array with appropriate colors based on the index.

const 
  evens = ["Red", "Black", "Blue"],
  odds = ["Maroon", "Gray", "Cyan"],
  result = Array.from(
    { length: 20 },
    (_, i) =>
      `${
        i & 1
          ? evens[Math.floor(i / 2) % evens.length]
          : odds[Math.floor(i / 2) % odds.length]
      } = ${i   1}`
  );

console.log(result);

  • Related