How can I implement Ruby's Array.include? in JavaScript?
Asked Answered
A

2

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?

Adventurism answered 17/11, 2010 at 10:59 Comment(1)
Similar Question: #237604Believe
P
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.

Peerage answered 17/11, 2010 at 11:3 Comment(1)
Yes, you are right. It is "indexOf". Thanks for additional info related to IE.Adventurism
E
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)
Egest answered 6/7, 2012 at 20:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.