1

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
}

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.