Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda