13

I need a javascript function that can take in a string and an array, and return true if that string is in the array..

 function inArray(str, arr){
   ...
 }

caveat: it can't use any javascript frameworks.

6 Answers 6

18

You could just make an array prototype function ala:

Array.prototype.hasValue = function(value) {
  var i;
  for (i=0; i<this.length; i++) { if (this[i] === value) return true; }
  return false;
}

if (['test'].hasValue('test')) alert('Yay!');

Note the use of '===' instead of '==' you could change that if you need less specific matching... Otherwise [3].hasValue('3') will return false.

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

1 Comment

Including the var in the for(...) is logically misleading, as it suggests the scope of the var is only inside the for loop (to multi-lingual programmers). However, the scope is the entire function. Also, declaring variables at the highest point in their scope is usually considered a good practice and a great way to avoid scope conflicts.
8

you can use arr.indexOf()

http://www.w3schools.com/jsref/jsref_indexof_array.asp

3 Comments

Interesting. This answer (.indexOf(.)) seems to work for my purpose. As a newbie am curious to know why a method in the language would have been less preferred to a custom function.
I realize the above is old but it's worth answering for future readers. array.indexOf() is Javascript 1.6. Older versions of Javascript, as those found in Internet Explorer, do not support it hence we would use a custom method/polyfill where needed.
MDN has a polyfill you can cut and paste in: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
8

Something like this?

function in_array(needle, haystack)
{
    for(var key in haystack)
    {
        if(needle === haystack[key])
        {
            return true;
        }
    }

    return false;
}

2 Comments

I probably should not have used for(key in array). If someone has extended the Array object then it will iterate over the new methods/properties as well (not just the array values).
-1 Better to use Array.prototype.indexOf(), fallback with a library such as underscore, jQurey etc., and finally if no library is wanted or available then use above solution except check Object.prototype.hasOwnProperty().
3

you can simply use : Array.prototype.includes()

Here is a demo :

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

Comments

1

Take a look at this related question. Here's the code from the top-voted answer.

function contains(a, obj) {
  var i = a.length;
  while (i--) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

Comments

-1

careful:

indexOf() uses partial data. if you have '12', '1'

indexOf('1') will get you the index of '12' not '1'

2 Comments

I think you are wrong I cannot down-vote you but could you please support your answer? my jsfiddle here proves that you are wrong
I think you confused the indexes, the above example would give you an index of one which is the right index for '1'. Always remember that the first array element has an index of zero which is the index of '12' Have a look at the exact replica of your example here

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.