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.
>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>