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.
source to share
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))
source to share
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)]);
source to share
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]);
}
source to share