23

If I have a list in Python, I can check whether a given value is in it using the in operator:

>>> my_list = ['a', 'b', 'c']

>>> 'a' in my_list
True

>>> 'd' in my_list
False

If I have an array in JavaScript, e.g.

var my_array = ['a', 'b', 'c'];

Can I check whether a value is in it in a similar way to Python’s in operator, or do I need to loop through the array?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
  • In other words, I’m asking [this question](http://stackoverflow.com/questions/1529986/ruby-methods-equivalent-of-if-a-in-list-in-python), but for JavaScript instead of Ruby. – Paul D. Waite Sep 16 '11 at 09:45
  • 2
    possible duplicate: http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – mouad Sep 16 '11 at 09:48
  • @6502: ah, that’s the stuff. Write that up into an answer and the points are yours. – Paul D. Waite Sep 16 '11 at 09:48
  • Check [this](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) qeustion. – denolk Sep 16 '11 at 09:49
  • @mouad: great spot — I’m actually using underscore.js, which the top answer to that question mentions, so I might use their function for this. – Paul D. Waite Sep 16 '11 at 09:49

4 Answers4

31

Since ES7, it is recommended to use includes() instead of the clunky indexOf().

var my_array = ['a', 'b', 'c'];

my_array.includes('a');  // true

my_array.includes('dd'); // false
FZs
  • 16,581
  • 13
  • 41
  • 50
Daniel Kim
  • 926
  • 1
  • 9
  • 17
15
var my_array = ['a', 'b', 'c'];
alert(my_array.indexOf('b'));
alert(my_array.indexOf('dd'));

if element not found, you will receive -1

Peter Porfy
  • 8,921
  • 3
  • 31
  • 41
  • 2
    In modern browser, yes, but older internet explorers does not support it. Here is a question about it (and the workaround): http://stackoverflow.com/questions/2790001/fixing-javascript-array-functions-in-internet-explorer-indexof-foreach-etc – Peter Porfy Sep 16 '11 at 09:57
  • what if searched item exists more than one in an array ? – Ciasto piekarz Dec 28 '18 at 17:32
  • @Ciastopiekarz indexOf returns the first occurrence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Peter Porfy Dec 28 '18 at 18:05
3
var IN = function(ls, val){
    return ls.indexOf(val) != -1;
}

var my_array = ['a', 'b', 'c'];
IN(my_array, 'a');
J. Doe
  • 305
  • 1
  • 11
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
1

The most current way with ES7 would be the following:

let myArray = ['a', 'b', 'c'];

console.log(myArray.includes('a'))

This will return true or false.

FZs
  • 16,581
  • 13
  • 41
  • 50