the_lorem_ipsum_guy
the_lorem_ipsum_guy

Reputation: 474

Create multidimensional array based by form input number

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!

Upvotes: 1

Views: 81

Answers (2)

Mitya
Mitya

Reputation: 34556

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})));

Upvotes: 0

Swati
Swati

Reputation: 28522

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>

Upvotes: 1

Related Questions