1

I have the following array in JavaScript which is used to create a list of fixtures for teams to play against each other.

[["a", "b", "c", "d"], ["a", "c", "b", "d"], ["a", "d", "b", "c"]]

My current code:

var f = "";     
   for (var z=0; z<matches.length; z++)
   {
     f += "Fixture " + (z + 1 ) + " " + matches[z] + "<br/>";
   }  
  document.getElementById("ln").innerHTML = f;
}

this outputs the array as:

Fixture 1 a,b,c,d
Fixture 2 a,c,b,d
Fixture 3 a,d,b,c

However I would like it to look like:

Fixture 1
a V b
c V d
Fixture 2
a V c
b V d

Basically I need to add a 'V' every second value after the first, and add an additional < br/ > after every 2 values.

Could someone help me out with this or point me in the right direction, please?

3
  • 1
    What seems to be a problem? Have you learned nested loops yet? Commented Jun 28, 2020 at 18:49
  • You can add one more loop for doing this. Commented Jun 28, 2020 at 18:51
  • I understand what nested loops are, however, I'm not too familiar with arrays like this. In this case, matches[z], the [z] can refer to ["a", "b", "c", "d"], however I'm not too sure how I can refer to just the team 'a', for example. Commented Jun 28, 2020 at 18:55

2 Answers 2

3

Try this. Upvote me if it works.

var f = "";     
   for (var z=0; z<matches.length; z++)
   {
     code1 = matches[z].slice(0,2).join(" V ");
     code2 = matches[z].slice(2).join(" V ");
     f += "Fixture " + (z + 1 ) + "<br/>" + code1 + "<br/>" + code2 + "<br/>";
   }  
  document.getElementById("ln").innerHTML = f;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I guess you didn't get upvoted because you asked for it, nice solution btw.
No issue. I am happy helping you.
Sorry, I did upvote but I don't have the reputation for it to show. I do appreciate the answer though!
2

spycbanda's code is good, but only works for four teams. By using an inner loop, you can handle an indefinite number of teams:

var f="";
for(var z=0; z<matches.length; z++) {
  f += "Fixture " + (z + 1) + "<br/>";
  for(let y=0; y<matches[z].length; y+=2)
    f+= matches[z][y] + " V " + matches[z][y+1] + "<br/>";
  f += "<br/>";   
}
document.getElementById("ln").innerHTML = f;

1 Comment

Thanks a lot, that's perfect!

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.