For loop with if else statement not iterating over entire array

I have been beating my head agains the wall with a basic JS for loop and if else statement. Unfortunately I can not figure it out so I am kindly seeking you advice.

I have added the code below and this is a link to jsfiddle - https://jsfiddle.net/mauro_nappolini/wv5ae1y2/25/#&togetherjs=FFtkmLmEvo

I have an for loop with a nested if else statement which is which does not iterate over the entire array. The for loop stops when the statement returns true and does not iterate over the remaining items in the array.

//Loops through and retrieves all emails from a class of jobemail and adds it to an 
array
var allEmails = $(".jobemail").map(function() {
  return this.innerHTML;
}).get();

//Gets the email that we want to use during comapariosion 
let membersEmail = $('.email-comparison').html();

//New array for all matching emails
let newArray = [];
console.log(membersEmail);
console.log(newArray);

//Loops through new array - shows only matching emails and hides emails that do not 
match
for (let i = 0; i < allEmails.length; i++) {
  console.log(allEmails[i]);
  if (allEmails[i] == membersEmail) {
    //Show matching email content container when jobeemail and email-comparison matches
    $(".email-content-container").show();
    newArray.push(allEmails[i])
  } else {
    //Hide matching email content container when jobeemail and email-comparison matches
    $(".email-content-container").hide();

  }
}
console.log(newArray);

1 answer

  • answered 2022-05-04 09:52 Abhay Prince

    What you should do is hide all before the loop, and then show the matching ones in the loop

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum