Home > Software engineering >  How to access only certain elements in a 2d array in Javascript?
How to access only certain elements in a 2d array in Javascript?

Time:10-02

goals a 2d array. I am trying to separate the items or the array but I cannot. The output of this would be 'run,3' or 'walk,2' etc. I want to just print the 'run' in one place and the '3' in another place, etc.

if (this.goals.length > 0) {
  for (i = 0; i < this.goals.length; i  ) {
    data  = '<tr>';
    data  = '<td>' (i 1)  '. '    this.goals[i]     '</td>';
    data  = '</tr>';
  }
}

The array is basically like this:

run,3               
walk,5              
swim,8

This is the output:

1. run,3                
2. walk,5               
3. swim,8

I want it to be more like: 'run' and '3' in separate table cells 'walk' and '5' in separate table cells

The idea being first the user enters a goal, and then the amount. I have the information stored in the array, but I can't separate it out.

CodePudding user response:

This can be more elegantly done with a map

const goals = [["run",3],["walk",5],["swim",8]];

if (goals.length > 0) document.getElementById("tb").innerHTML = goals
  .map(([name, val], i) => `<tr><th>${i 1}.</th><td>${name}</td><td>${val}</td></tr>`)
  .join("");
<table>
  <tbody id="tb"></tbody>
</table>

CodePudding user response:

this.goals[i] should be ['walk',2] or ['run',3] right ?

If that is the case, then you can just access that array values like:

if (this.goals.length > 0) {
  for (i = 0; i < this.goals.length; i  ) {
    const action = this.goals[i][0]
    const number = this.goals[i][1]
    data  = '<tr>';
    data  = '<td>' (i 1)  '. '     action    ''   number   '</td>';
    data  = '</tr>';
  }
}
  • Related