I have two arrays of string with dynamic lenght, for example:
JavaScript
x
3
1
const categories = ['apple', 'pear', 'melon', 'lemon']
2
const colors = ['red', 'blue', 'green']
3
and I would like that colors.lenght >= categories.lenght
. Missing element of colors
should be repeated. Example:
JavaScript
1
3
1
const categories = ['apple', 'pear', 'melon', 'lemon']
2
const colors = ['red', 'blue', 'green', 'red'] // colors[3] = colors[0]
3
JavaScript
1
3
1
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange']
2
const colors = ['red', 'blue', 'green', 'red', 'blue', 'green']
3
JavaScript
1
3
1
const categories = ['apple', 'pear', 'melon', 'lemon', 'strawberry', 'orange', 'cherry']
2
const colors = ['red', 'blue', 'green', 'red', 'blue', 'green', 'red']
3
How can I do that?
I start creating this function but I don’t know how to repeat colors in the right way:
JavaScript
1
8
1
function adjustLenghts(categories: string[], colors: string[]) {
2
const overflowingCategoriesItems = domain.slice(colors.length, categories.length)
3
const repeatedRange = ??
4
const newColors = ??
5
6
return newColors
7
}
8
Advertisement
Answer
you can do something like this
JavaScript
1
7
1
const categories = ['apple', 'pear', 'melon', 'lemon', 'banana']
2
const colors = ['red', 'blue', 'green']
3
4
5
const adjustedColor = categories.map((_, i) => colors[i % colors.length])
6
7
console.log(adjustedColor)