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
Share
Improve this question
edited Jul 15, 2020 at 20:15
Unmitigated
89.4k12 gold badges93 silver badges103 bronze badges
asked Jul 15, 2020 at 20:06
ndemasiendemasie
6101 gold badge7 silver badges17 bronze badges
2
-
1
What is the significance of the content in
items
here? You only seem to use its length... – trincot Commented Jul 15, 2020 at 20:09 - Does this answer your question? Concise way to return a new array of N elements filled with iterated values from another array? Vanilla JavaScript – VLAZ Commented Jul 15, 2020 at 20:13
6 Answers
Reset to default 7
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);
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));
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);
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);