Sergi
Sergi

Reputation: 1240

Iterate through a 2d Array and listing all of the entries

I have a function that iterates through a 2d Array, every Array has a song and an interpreter and the function is supposed to run a loop and list every song with it's interpreter. The problem is that it only lists the last song and interpreter, what am I missing so it lists all of them?:

HTML:

<ul id="2d"> </ul>

JS

var twoDArray = [
  ["I did it my way", "Frank Sinatra"],
  ["Respect", "Areta Franklin"],
  ["Imagine", "John Lennon"]
];

function iterative( songs ) {
  for ( var i = 0; i < songs.length; i += 1) {
    document.getElementById("2d").innerHTML =  "<li>" + songs[i][0] + " by " + songs[i][1] + "</li>";
 }
}

iterative(twoDArray);

Upvotes: 0

Views: 48

Answers (2)

ONMNZ
ONMNZ

Reputation: 328

Here's one way. Hope this helps.

const twoDArray = [
  ["I did it my way", "Frank Sinatra"],
  ["Respect", "Areta Franklin"],
  ["Imagine", "John Lennon"]
];
const ul = document.querySelector('ul');
twoDArray.forEach(pair => {
  const li = `<li>${pair[0]} by ${pair[1]}</li>`;
  ul.insertAdjacentHTML('beforeend', li);
})
HTML:

<ul id="2d"> </ul>

Upvotes: 0

gh9
gh9

Reputation: 10703

That is because you are setting the innerHtml every time you loop, so it will over-write itself every time except the last. You want to do this instead

  document.getElementById("2d").innerHTML +=  "<li>" + songs[i][0] + " by " + songs[i][1] + "</li>";

Upvotes: 4

Related Questions