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

145
Vistas
How to make a black and white two column alternating grid with javascript

I am mapping through an array and want the output to be the following:

Array.from([1,2,3,4,5,6,7,8,9,10]).map((number, index) => console.log(index))

// 0-white 1-black 2-black 3-white 4-white 5-black 6-black 7-white 8-white 9-black

How can I do this using the index of Array.map?

For context, I am mapping through a list of items to display on a two column grid. I need to use JS, therefore the index needs to infer the correct color and can't use CSS in this scenario.

I can't for the life of me figure out the math logic to get the color correct.

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

One way to do this is to XOR the lowest 2 bits of index, that will give you a pattern of 0,1,1,0 which can then be translated into black and white:

result = Array.from([1,2,3,4,5,6,7,8,9,10])
  .map((_, index) => (index & 1) ^ (index >> 1 & 1) ? 'black' : 'white')

console.log(result)

about 4 years ago · Santiago Gelvez Denunciar

0

Some thing like

const pattern = ["white", "black", "black", "white"];
  
Array.from([1,2,3,4,5,6,7,8,9,10]).map((_, i) => {
  console.log(i, pattern[i % pattern.length])
})

about 4 years ago · Santiago Gelvez 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