Reputation: 610
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
Upvotes: 4
Views: 2121
Reputation: 5547
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);
Upvotes: 1
Reputation: 17590
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)])
}
Upvotes: 2
Reputation: 386560
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);
Upvotes: 3
Reputation: 350167
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));
Upvotes: 3
Reputation: 89224
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);
Upvotes: 3
Reputation: 18592
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);
Upvotes: 7