How do I repeat the colors array in order, given an unknown length of items?
const items = [1, 2, ...n]
const colors = ['blue', 'green', 'red']
// return ['blue', 'green', 'red', 'blue', 'green'] where items.length = 5
How do I repeat the colors array in order, given an unknown length of items?
const items = [1, 2, ...n]
const colors = ['blue', 'green', 'red']
// return ['blue', 'green', 'red', 'blue', 'green'] where items.length = 5
const items = [1, 2, 3,4,5,6,7,8]
const colors = ['blue', 'green', 'red']
const result = items.map((_,i) => colors[i%colors.length]);
console.log(result);
You can map over a new array with the length you want and take the modulus of the index by the length of the colors array. You do not seem to need the items array at all.
let len = 5;
const colors = ['blue', 'green', 'red'];
const res = Array(len).fill().map((_,idx)=>colors[idx % colors.length]);
console.log(res);
Array.from can also be used in this case.
let length = 5;
const colors = ['blue', 'green', 'red'];
const res = Array.from({length}, (_,idx)=>colors[idx % colors.length]);
console.log(res);
Create a new array and map the values by using the remainder operator %.
const
items = [1, 2, 3, 4, 5, 6, 7, 8],
colors = ['blue', 'green', 'red'],
result = Array.from(items, (_, i) => colors[i % colors.length]);
console.log(result);
When the target size is large, you may get better performance by doubling the array over and over again:
function stretch(arr, n) {
while (arr.length < n) arr = arr.concat(arr);
return arr.slice(0, n);
}
const items = [1, 2, 3, 4, 5];
const colors = ['blue', 'green', 'red'];
console.log(stretch(colors, items.length));
You can take mode for index so you can repeat it.
const items = [1, 2, 3,4,5,6];
const colors = ['blue', 'green', 'red'];
var result=[];
items.forEach(myFunction)
function myFunction(item, index) {
console.log(colors[(index%colors.length)])
result.push(colors[(index%colors.length)])
}
Using map()
const items = [1, 2, 3, 4, 5, 6, 7, 8],
colors = ['blue', 'green', 'red'];
output = items.map((_,i) => colors[i % colors.length])
console.log(output);