Abraham
Abraham

Reputation: 45

How to avoid the skipping of the array index in a second array?

How can I not skip the elements of the array of the year?

I want the result to be:

Banana
0
Mango
1

Current result:

Banana
0
Mango
3

Code here:

<body>
<p id="demo"></p>
<script>
    var fruits, text, year, i;
    fruits = ["Banana", "Orange", "Apple", "Mango"];
    year = ["0", "1", "2", "3"];
    text = "<ul>";
    for (i = 0; i < fruits.length; i++) {
        switch (fruits[i]) {
            case 'Mango':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Pine apple':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Grape':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Banana':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
        }
    }
    text += "</ul>";
    document.getElementById("demo").innerHTML = text;
</script>

Upvotes: 4

Views: 142

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

Loop through the Arrays as you do and increment a second counter for when a fruit matches one of the case statements. Use the counter to get the year number from the array:

var fruits, text, year, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
year = ["0", "1", "2", "3"];
text = "<ul>";
let counter = 0; // <-- define a second counter
for (i = 0; i < fruits.length; i++) {
  switch (fruits[i]) {
    case 'Mango':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++; // <-- that only get's incremented when a case is matched
      break;
    case 'Pine apple':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
    case 'Grape':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
    case 'Banana':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
  }
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

Upvotes: 2

Related Questions