skip to Main Content

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


  1. 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:

    outputLength % baseLength == indexIntoBaseList
    0 % 3 == 0
    1 % 3 == 1
    2 % 3 == 2
    3 % 3 == 0
    4 % 3 == 1
    5 % 3 == 2
    

    This gives you a repeating pattern of indices into your base list that you can use to add the correct item.

    function RepeatListToLength(baseList, maxLength) {
        var output = [];
        while(output.length < maxLength) {
            output.push(baseList[output.length % baseList.length]);
        }
        return output;
    }
    
    console.log(RepeatList([1,2,3,4,5], 13));
    Login or Signup to reply.
  2. 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.

    function repeatToLength(source, size) {
        const iterations = Math.ceil(size / source.length);
        return Array(iterations).fill(source).flat().slice(0, size);
    }
    
    console.log(repeatToLength(['a', 'b', 'c'], 5));
    Login or Signup to reply.
  3. 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:

    const repeatToLength = (arr, len) => arr.length < len ?
      repeatToLength([...arr, ...arr], len) : arr.slice(0, len);
    
    console.log(repeatToLength(['a', 'b', 'c'], 5));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search