Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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);
});

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda