Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access only certain elements in a 2d array in Javascript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading