12

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.

Jacob
  • 77,566
  • 24
  • 149
  • 228
RobKohr
  • 6,611
  • 7
  • 48
  • 69

6 Answers6

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.

gnarf
  • 105,192
  • 25
  • 127
  • 161
  • 3
    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. – Kato Nov 08 '11 at 18:22
8

you can use arr.indexOf()

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

Shin Akuma
  • 396
  • 1
  • 5
  • 8
  • 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. – prototype Oct 27 '12 at 03:25
  • 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. – n0wak Mar 28 '13 at 23:44
  • MDN has a polyfill you can cut and paste in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – William Turrell Feb 21 '14 at 23:29
8

Something like this?

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

    return false;
}
Matthew
  • 3,086
  • 2
  • 20
  • 9
  • 5
    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). – Matthew May 21 '09 at 00:11
  • -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(). – martin Dec 08 '13 at 22:47
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
LoickMEYER
  • 50
  • 2
  • 14
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;
}
Community
  • 1
  • 1
Dan Walker
  • 7,123
  • 6
  • 30
  • 24
-1

careful:

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

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

  • I think you are wrong I cannot down-vote you but could you please support your answer? my jsfiddle [here](http://jsfiddle.net/DDWr6/) proves that you are wrong – Andreas Oct 13 '13 at 21:03
  • 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](http://jsfiddle.net/DDWr6/) – Andreas Oct 13 '13 at 21:11