markbuzz
markbuzz

Reputation: 31

Printing array values by a repeating pattern

var arr = [a, b, c];

In above array, index 0 contains "a", index 1 contains "b", index 2 contains "c".

console.log(arr[0])  // will print > "a"
console.log(arr[1])  // will print > "b"
console.log(arr[2])  // will print > "b"

Is there a way so that if I want to console.log(arr[3]) then it should print "a" again, console.log(arr[4]) would be "b" and so on. If we want an index of let's say 42 like this console.log(arr[42]) then it should print any of those three string values by following the same pattern.

Upvotes: 3

Views: 95

Answers (4)

Tevon Strand-Brown
Tevon Strand-Brown

Reputation: 1708

Using % you can have it repeat as many times as you like.

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

let repetitions = 5;

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

Upvotes: 1

Ami
Ami

Reputation: 357

We can define our custom function which give the appropriate index

function getIndex(num){
  return num%3;/* modulo operator*/ 
}
var arr=["a","b","c"];
console.log(arr[getIndex(0)]);
console.log(arr[getIndex(1)]);
console.log(arr[getIndex(2)]);
console.log(arr[getIndex(3)]);
console.log(arr[getIndex(4)]);
console.log(arr[getIndex(5)]);
console.log(arr[getIndex(41)]);

Upvotes: 2

prasanth
prasanth

Reputation: 22500

simply use with % like this arr[value % arr.length].

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

function finding(val){
return arr[val % arr.length];
}
console.log(finding(0))
console.log(finding(1))
console.log(finding(2))
console.log(finding(3))
console.log(finding(4))
console.log(finding(5))
console.log(finding(6))
console.log(finding(42))

Upvotes: 3

Jins Peter
Jins Peter

Reputation: 2469

We cannot have exactly what you are looking for. But what we can have what you are looking for by this

var arr = ["a","b","c"];
var printToThisIteration = function(n){
    var length = arr.length;
    for(i=0;i<n;++i)
     {
         console.log(arr[i%length])

     }
}

Upvotes: 1

Related Questions