Home > Back-end >  How to make a black and white two column alternating grid with javascript
How to make a black and white two column alternating grid with javascript

Time:06-14

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.

CodePudding user response:

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)

CodePudding user response:

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

  • Related