3
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.

4 Answers 4

3

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))

Sign up to request clarification or add additional context in comments.

1 Comment

Straightforward and elegant solution.
2

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)]);

Comments

1

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])

     }
}

Comments

1

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.