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

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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