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);
Array.from({length: 5}, (_, i) => colors[i % colors.length])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));
map / Array.from solution over this unless I expected large arrays. But when wanted, this is quite useful.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);
map call?map, i miss the part where an element is used for the result. (this may apply here as well ...)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)])
}
map in disguise. You might as well just use it directly.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);
[... and trailing ]. The map call already creates a new array that does what we want. The spread is entirely superfluous.
itemshere? You only seem to use its length...