0

I have an array mainTitle that I am attempting to check if the string exists in listOfTitles then append to #mainTitle. If not then append to #otherTitle. In order to achieve this, I am looping through the array listOfTitles in order to check if any of the strings match with the first index of mainTitle

My issue is that string appends for every time the check fails due to the length of the array I am looping through. In this example, "Online" should only appear once in blue text, and "Retail" and "Store" which doesn't exist in listOfTitles should only appear once in red text.

I am attempting to have the string append-only once. How can I achieve with when needing to increment through the entire array in order to check if there is a match?

My expected outcome is to have only 1 "Online", "Retail", and "Store" to append and not the length of the string.

const mainTitle = ["Online", "Retail", "Store"]

const listOfTitles = ["Test","Test2","Test3","Test4","Test5","Test6", "Online", "Test7"]


for (let i = 0; i < mainTitle.length; i++) {
 

checkMatch(mainTitle[i])

};

function checkMatch (title) {

for (let i = 0; i < listOfTitles.length; i++) {

if (title=== listOfTitles[i]) {
$("#mainTitle").append(title);
} else {
$("#otherTitle").append(title);
}


}

}
#mainTitle {
color:blue;
}

#otherTitle {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainTitle"> </div>
<div id="otherTitle"> </div> 

1 Answer 1

1

You shouldn't be appending because every time the loop runs, something will get added. Instead, just replace the contents of the target element with the new results.

const mainTitle = ["Online", "Retail", "Store"]
const listOfTitles = ["Test","Test2","Test3","Test4","Test5","Test6", "Online", "Test7"]
for (let i = 0; i < mainTitle.length; i++) {
  checkMatch(mainTitle[i])
};

function checkMatch (title) {
  for (let i = 0; i < listOfTitles.length; i++) {
    if (title=== listOfTitles[i]) {
      $("#mainTitle").text(title);
    } else {
      // Only append if the title is not already in the element
      if(!$("#otherTitle").text().includes(title)){
        $("#otherTitle").append(title);
      }
    }
  }
}
#mainTitle {
  color:blue;
}

#otherTitle {
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainTitle"></div>
<div id="otherTitle"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain what the else code is doing? Starting with the comment Only append if the title is not already in the element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.