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

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

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 Report

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