Varun Chakervarti
Varun Chakervarti

Reputation: 1042

How to print array repeatedly with a specified number of times

I have an array for example:

var arr = ['a','b','c','d'];

Now I will ask user to insert a number for example: 6 or 7 or 10 or any number.

Lets take an example that user has enter: 10

Now the output should be: a b c d a b c d a b

total of 10 values should get print using the array values in order.

But the main problem is that there should be No if condition

Upvotes: 1

Views: 703

Answers (2)

bvx89
bvx89

Reputation: 888

Normally:

for (var i = 0; i < input; i++) {
  console.log(arr[i%arr.length]);
}

Recursively:

var f = function(input) {
  return input > 0 ? f(input-1)+arr[input%arr.length] : arr[0];
}

console.log(f(10));

Upvotes: 1

rdubya
rdubya

Reputation: 2916

You need to make use of the modulus operator (%). Docs here

Pseudo code:

loop with index i
    output yourArray[i % yourArray.length]
end loop

Upvotes: 5

Related Questions