Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating over array to check whether strings “`includes“` another string

using the includesmethod to check whether strings in an array include another string. Basically like a search function type of thing.

Heres what I have so far

this.findIngredient = function(ingredientName) {
          for (i=0; i < this.ingredients.length; i++) {
               if (this.ingredients[i].includes(ingredientName)) {
                     return true
                     break
                 } else {
                    return false
                   }
                }
            }

what im unsure about is why when the this.ingredient does hold a string that includes ingredientName it still outputs false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For context this is the this.ingredient array

this.ingredients = ["500g plain flour", "1 tsp fine salt", "2 heaped tsp baking powder"]

>Solution :

Removing the else block from within your loop should resolve the issue.

Explanation –

The else block is run when this.ingredients[i].includes(ingredientName) is false. And in your code, when the else block returns false which means your loop will not have the opportunity to check every element in the ingredients array since the function will stop execution when it sees a return statement.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading