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

241
Views
Repeat elements in array based on length of another array

I have two arrays of string with dynamic lenght, for example:

const categories = ['apple', 'pear', 'melon', 'lemon']
const colors = ['red', 'blue', 'green']

and I would like that colors.lenght >= categories.lenght. Missing element of colors should be repeated. Example:

const categories = ['apple', 'pear', 'melon', 'lemon']
const colors = ['red', 'blue', 'green', 'red'] // colors[3] = colors[0]
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange']
const colors = ['red', 'blue', 'green', 'red', 'blue', 'green']
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange', 'cherry']
const colors = ['red', 'blue', 'green', 'red', 'blue', 'green', 'red']

How can I do that?

I start creating this function but I don't know how to repeat colors in the right way:

function adjustLenghts(categories: string[], colors: string[]) {
  const overflowingCategoriesItems = domain.slice(colors.length, categories.length)
  const repeatedRange = ??
  const newColors = ??

  return newColors
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can do something like this

const categories = ['apple', 'pear', 'melon', 'lemon', 'banana']
const colors = ['red', 'blue', 'green']


const adjustedColor = categories.map((_, i) => colors[i % colors.length])

console.log(adjustedColor)

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!