How can I get the following effect?
On the input of the number 5 and the following array:
const list = ['a', 'b', 'c'];
It should produce the following output:
['a', 'b', 'c', 'a', 'b'] // Total 5
I tried for and while, but I don’t know how to restart the loop when the loop exceeds the length of the list.
3
Answers
You can do this by repeatedly adding items from your starting list (
baseList
below) until you reach the desired length.You can get the correct index in the base list by using the modulo operator (
%
) to get the remainder of division from dividing your output list’s length by the base list’s length, for example:This gives you a repeating pattern of indices into your base list that you can use to add the correct item.
Figure out how many times to repeat the entire list in order to have enough elements; do that repetition using
Array.fill
and.flat
; then truncate using.slice
.Here’s a recursive variant. The repeatToLength function calls itself with a new array consisting of two old arrays until it reaches enough length and then slices the final array to the exact length required: