1

Not entirely sure if this one already existed but if it is please provide a link since I haven't found anything.

I have a textbox of a number of teams. If I input 4 in the textbox and click a button to generate an array, below would be the desired output. There will be 2 teams per array.

If input 6 in the textbox then the output would be 2 teams in 3 arrays. If input 12, then it would be 2 teams in 6 arrays.

Desired output:

[{name: "Team 1"}, {name: "Team 2"}],
[{name: "Team 3"}, {name: "Team 4"}]

This is what I've tried so far but I only get it when I inputted 4 in the textbox.

[{name: "Team 1"}, {name: "Team 2"}]
$('#form').on('submit', function(e) {
    e.preventDefault();
    var numOfTeam = $('#num-of-team').val();

    var teams = [];

        for (let i = 1; i <= numOfTeam; i++) {
            var team = {name: ""};
            if (i % 2 === 0) {
                teams.push(team);
            }
        }
        console.log(teams)
    ....

Need your thoughts on this. Thanks in advance for your help!

2
  • So the logic is there should be two teams per array? Commented Feb 4, 2021 at 12:24
  • @Mitya yes, there is I will update the post thanks Commented Feb 4, 2021 at 12:24

2 Answers 2

1

You can create one main_array and push your value inside main_array when i%2==0 condition and then empty teams array .

Demo Code:

var numOfTeam = 6 //suppose input

var main_array = [];
var teams = []
for (let i = 1; i <= numOfTeam; i++) {
  var team = {
    name: i
  };
  teams.push(team);
  if (i % 2 === 0) {
    main_array.push(teams) //push in main_array
    teams = [] //empty teams
  }
}
console.log(main_array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

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

1 Comment

Sweet! didn't realize I need to create another array. Thanks for this!
0

A short way, if admittedly less readable (adapted from this reference):

let numTeams = 6,
    chunk = 2,
    teams = Array(Math.ceil(numTeams / chunk)).fill(0);
teams = teams.map((x, i) => Array(chunk).fill().map((x, i2) => ({name: i * chunk + i2 + 1})));

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.