Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!