0

I'm taking a JavaScript class and for an exercise we have to compare an array to another array, and replace the inner html text of an element with only the string values that exist in BOTH arrays. Here is the javascript:

// Here is an array of US State Capitals to use
var capitals = ["Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover", "Tallahassee", "Atlanta", "Honolulu", "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka", "Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston", "Lansing", "Saint Paul", "Jackson", "Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany", "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia", "Pierre", "Nashville", "Austin", "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"];



// Using JavaScript, get the contents of the "cities" div and convert it into an array of strings (each city will be an element in the array)
var citiesString = document.getElementById("cities").innerHTML;

var cities = citiesString.split(", ");


// Loop through the array of cities.  Compare each element to the array of capitals.  If a city is NOT a state capital, update the HTML output to leave out that city.  (Note: formatting, commas, etc. doesn't count -- just get the cities to display.)


for (i = 0; i < cities.length; i++) {
  if(capitals.indexOf(cities[i]) >=0) {
    document.getElementById("cities").innerHTML += cities[i] += ", ";
  } 
}

I have it displaying only the cities present in both arrays, but it is still displaying the entire list of the cities array before hand. How do I get it to display only "Boston, Indianapolis, and Atlanta"?

1
  • Please show the data inside the cities Commented Feb 20, 2018 at 4:11

1 Answer 1

2

clear the content of the 'cities' before the for loop.

document.getElementById("cities").innerHTML = "";

you were appending your your array to the existing text in your element.

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

1 Comment

Thanks! I added this before the for loop and it's working now.

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.