MTimo27
MTimo27

Reputation: 33

How can I loop this array?

var today = new Date();
if (today.getDay() == 6 || today.getDay() == 0) {

  document.getElementById("name1").innerHTML = "WEEKEND";
  document.getElementById("name2").innerHTML = "WEEKEND";

} else {

  var d = new Date().getDay();
  var names1 = ['1', '2', '3'];
  var names2 = ['1', '2', '3', '4'];
  var n1 = names1.length;
  var n2 = names2.length;

  for (var i = 0; i < n1; i++) {
    document.getElementById("name1").innerHTML = names1[d - 1];
  }

  for (var j = 0; j < n2; j++) {
    document.getElementById("name2").innerHTML = names2[d - 1];
  }
}

I need to show on screen 2 numbers from these arrays, but the arrays aren't equal so I want the array that is shorter to start again and form pairs with the remaining numbers from the longer array.

Basically the premise is to show 1 name from each group every workday on screen.

EX:

1 1
2 2
3 3
1 4
2 1
3 2

etc.

Upvotes: 1

Views: 87

Answers (3)

Jacek Rojek
Jacek Rojek

Reputation: 1122

Total number of possible combinations would be the multiplication of arrays length n1*n2

var d = 1; // new Date().getDay()
var names1 = ['1', '2', '3'];
var names2 = ['1', '2', '3', '4'];
var n1 = names1.length;
var n2 = names2.length;

for (var i = 0; i < n1 * n2 ; i++) {
  console.log(names1[i%n1], names2[i%n2]);
}

Also you have redundant code, use only one variable for date

var today = new Date().getDay()
if (today == 6 || today == 0) {

  document.getElementById("name1").innerHTML = "WEEKEND";
  document.getElementById("name2").innerHTML = "WEEKEND";

} else {
  // var d is the same as var today

Upvotes: 2

wxker
wxker

Reputation: 1896

An elegant solution would use the % (modulo) operator. This operator gives you the remainder after the first operand is divided by the second operand.

For example:

7 % 2 = 1

8 % 5 = 3

If I understand your code correctly, you just want to display two numbers, one in each document element of ids name1 and name2 respectively. In that case, there is no need for a loop.

document.getElementById("name1").innerHTML = names1[d % n1];
document.getElementById("name2").innerHTML = names1[d % n2];

Upvotes: 1

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

Here you go:

var N = 20; // or whetever
var arr1 = [1, 2, 3];
var arr2 = [1, 2, 3, 4];

var res = [];
for(var i=0; i<N; i++){
  res.push(arr1[i%arr1.length]);
  res.push(arr2[i%arr2.length]);
}
console.log(res);

So in general, for any step N your pier is arr1[N%arr1.length], arr2[N%arr2.length]

Upvotes: 2

Related Questions