Skip to content
Advertisement

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
}

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement