Printing array values ​​with a repeating pattern

var arr = [a, b, c];

      

In the 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 console.log(arr[3])

then it should print again "a"

, console.log(arr[4])

will "b"

and so on. If we want a let say 42 index like this console.log(arr[42])

, then it should print any of these three string values, following the same pattern.

+3


source to share


4 answers


just use with the %

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

Run codeHide result


+3


source


We can define our custom function which gives the corresponding 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)]);
      

Run codeHide result


+2


source


We cannot know exactly what you are looking for. But what can we 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])

     }
}

      

+1


source


Using %

, you can repeat it 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]);
}
      

Run codeHide result


+1


source







All Articles