1

I have this challenge which in my head seems easy enough, but I can't seem to get my function right.

The challenge is as follows:

Create a function that determines if a given name is amongst the names.

So here is my array and function -

 var family = ["Steve", "John", "Dani", "Bob"];

 function searchName(f){
   for (i=0; i<family.length; i++){
     if ((family.lastIndexOf(f) != family[i]))
       {family[i]}
   }
 }

 searchName("Moe");

Now all this returns is undefined. Which is better than errors I suppose. What I want it to do is when I pass through a name that is not in the array to have it return a false statement, and if a name that is in the array, true. I also know that I need to throw in .toUpperCase and .toLowerCase in there as well to account for the case sensitivity. My assumption is that rather than just an if statement, I need an if/else if/ else.

Amir
  • 11
  • 3
  • 2
    I suggest you look over the methods available on arrays. You will find `indexOf` which already does what you want. It will return -1 if there's no match, or an index greater than or equal to zero if there is. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. –  Jan 28 '16 at 06:26
  • 2
    `alert(["Steve", "John", "Dani", "Bob"].includes("Moe"))` – dandavis Jan 28 '16 at 06:27
  • http://stackoverflow.com/a/143863/3399676 – ClearBoth Jan 28 '16 at 06:27
  • `alert(/\bMoe\b/.test(["Steve", "John", "Dani", "Bob"]))` – dandavis Jan 28 '16 at 06:28
  • `alert(["Steve", "John", "Dani", "Bob"].some(/./.test, /\bMoe\b/))` – dandavis Jan 28 '16 at 06:29
  • Your function returns undefined because you have no `return` statement. Using a for loop to test each item in the array is one way to do it, but if you do that you don't want `lastIndexOf()`, you want something like `if (f === family[i]) { return true; }` and then put a `return false;` after the loop. You don't need an else block. – nnnnnn Jan 28 '16 at 06:30
  • @dandavis could you please explain that line of code? alert(["Steve", "John", "Dani", "Bob"].some(/./.test, /\bMoe\b/)) – Amir Jan 28 '16 at 06:33
  • some returns true/false based on any array element causing the callback to return true-ish. the callback function i use tests the element against the RegExp, and if it matches, the iteration is stopped and true is returned. – dandavis Jan 28 '16 at 06:36

0 Answers0