8

I have an array tempArray = ["Kathmandu","Pokhara","Dharan"]. To make sure that "Pokhara" is in tempArry, I have to use loop and check every element of tempArray.

Is there a way to implement Ruby's Array.include? so that I don't need to use a loop?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ashisrai_
  • 6,438
  • 2
  • 26
  • 42
  • Similar Question: http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – ecleel May 22 '12 at 14:15

2 Answers2

6

You can use Array.indexOf to search for a value:

var includePokhara = ( tempArray.indexOf("Pokhara") >= 0 );

Unfortunately, Array.indexOf is not implemented in Internet Explorer, but you can look on StackOverflow how to add it back.

Community
  • 1
  • 1
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
4

EDIT - in es6 you can just use includes:
'Blue Whale'.includes('blue'); // returns false

You can also use jQuery for that, which has more elegant way to write it:

$.inArray(value, array)
Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55