Skip to content
Advertisement

Using a for loop with a function in Javascript [closed]

I am having trouble figuring out how to solve this challenge below:

Challenge: droids

Complete the function droids that accepts an array of strings and iterates through the array using a FOR loop. Update the variable result to “Found Droids!” if the array contains the string “Droids”. Otherwise update the variable result to “These are not the droids you’re looking for.” Return your updated result.

Here is the code written so far:

function droids(arr) {
  let result = '';
  // ADD CODE HERE
  return result;
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"] 
 const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"] 
 console.log(droids(starWars)) // should log: "Found Droids!"
 console.log(droids(thrones)) // should log: "These are not the droids you're looking for."

Can someone please help with find out what I need to add to solve this problem using javascript? Thank you so much

Advertisement

Answer

You can iterate through arr and return Found Droid as soon as you find it, or if not found return with not found.

Simple approach as below.

function droids(arr) {
  for(var str of arr) {
      if (str  === 'Droids') {
       return 'Found Droid';
    }
  }
 return `These are not the droids you're looking for`;
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) // should log: "These are not the droi
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement