739

Can someone tell me how to detect if "specialword" appears in an array? Example:

categories: [
    "specialword"
    "word1"
    "word2"
]
Cofey
  • 11,144
  • 16
  • 52
  • 74
  • In pure JS: http://stackoverflow.com/a/25765186/1320932 – dr.dimitru Sep 10 '14 at 12:19
  • 28
    pure JS : categories.includes("specialword") – patz Apr 12 '16 at 17:50
  • 4
    @patz watch out for pure JS, not supported in IE (any version) [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – foxontherock Dec 12 '17 at 15:29
  • @foxontherock start using transpiler - stop worrying about anything fact-checking, can-I-use-this-property kinda thing. – Alex Pogiba Aug 23 '18 at 06:52
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – gre_gor May 03 '23 at 18:20

7 Answers7

1154

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

Black
  • 18,150
  • 39
  • 158
  • 271
James
  • 30,496
  • 19
  • 86
  • 113
  • 2
    James, that page does say it will work in IE9, as I indicated. Did you get it work for IE < 9 ? I believe I've run into this feature as missing in IE7 and IE8, but did not actually test; instead I relied on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility – Michael Paulukonis Jun 19 '13 at 18:21
  • 23
    indexOf is available in all major browsers, except IE < 9 – Michael Paulukonis Jun 19 '13 at 18:22
  • 1
    what about `'foo' in arr`? – SuperUberDuper Mar 26 '15 at 15:01
  • 4
    @SuperUberDuper: That checks for if an object key exists: `1 in ['a'] -> false` `1 in ['a', 'b'] -> true` `'length' in [] -> true` It just so happens in JS an array is essentially an object with numeric keys. – Will S Mar 31 '15 at 11:25
  • 4
    http://needsmorejquery.com – Fusseldieb Aug 27 '18 at 19:43
  • @James nice solution. I really like your use of "I like turtles". would be good for a split and join demo too. – Ian Poston Framer Apr 06 '19 at 22:24
688

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;

console.log(foundPresent, foundNotPresent); // true false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.indexOf('specialword') > -1;
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;

console.log(foundPresent, foundNotPresent); // true false

Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern Javascript is Array.prototype.includes:

var found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');

console.log(foundPresent, foundNotPresent); // true false
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
38

Here you go:

$.inArray('specialword', arr)

This function returns a positive integer (the array index of the given value), or -1 if the given value was not found in the array.

Live demo: http://jsfiddle.net/simevidas/5Gdfc/

You probably want to use this like so:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
25

we can use includes option (which is js built-in function), which will return true if the value is found else it will be false.

if you want the exact index you can use indexOf (which is also js built-in function), which will return the exact index if the value is found else it will return -1.

You can switch .includes with the .some method which returns a boolean. It will exit as soon as a match was found, which is great for performance for huge arrays:

Note: all are case sensitive

var myarr = ["I", "like", "turtles"];

isVal = myarr.includes('like')
index = myarr.indexOf('like')
some = myarr.some(item => item.toLowerCase() == 'like'.toLowerCase())


console.log(isVal)
console.log(index)
console.log(some)

please check this.

Selva Ganapathi
  • 982
  • 10
  • 21
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Nov 24 '21 at 22:25
17

You can use a for loop:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}
Community
  • 1
  • 1
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 18
    I may be totally wrong on this, but wouldn't you want to declare i in the for loop? If you don't put "var" in front, it'll put it in the global context (I think...), which might not be what you want. – aendra Jul 11 '13 at 10:24
  • 7
    while that is true, that really isn't the point of what he is saying here. Don't ignore the forest for a few trees. – Chris Jones Feb 26 '14 at 18:50
  • 5
    @ChrisJones Given that JS-amateurs will copy and paste this answer into their code, the better it should be – cja Sep 07 '16 at 16:42
  • fwiw: you can now do something like: `const found = categories.any(c => c === "specialword");` – Luc H Jun 04 '23 at 16:14
12

With modern javascript's Array methods:

Array.prototype.includes() // introduced in ES7:

  • returns boolean

const data = {
  categories: [
    "specialword",
    "word1",
    "word2"
  ]
}

console.log("Array.prototype.includes()")
// Array.prototype.includes()
// returns boolean
console.log(data.categories.includes("specialword"))
console.log(data.categories.includes("non-exist"))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array.prototype.find() // introduced in ES6:

  • returns found element or undefined

const data = {
  categories: [
    "specialword",
    "word1",
    "word2"
  ]
}

console.log("Array.prototype.find()")
// Array.prototype.find()
// returns the element if found
// returns undefined if not found
console.log(data.categories.find(el => el === "specialword") != undefined)
console.log(data.categories.find(el => el === "non-exist") != undefined)
.as-console-wrapper { max-height: 100% !important; top: 0; }
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
7

I don't like $.inArray(..), it's the kind of ugly, jQuery-ish solution that most sane people wouldn't tolerate. Here's a snippet which adds a simple contains(str) method to your arsenal:

$.fn.contains = function (target) {
  var result = null;
  $(this).each(function (index, item) {
    if (item === target) {
      result = item;
    }
  });
  return result ? result : false;
}

Similarly, you could wrap $.inArray in an extension:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}
Adam Eberlin
  • 14,005
  • 5
  • 37
  • 49
  • 7
    (I'm not the downvoter) I'm not sure I understand the derision of $.inArray while wrapping up a method that relies on $(selector).each(). The actual inArray code simply uses indexOf for browsers that support it natively or a for loop like Jared's answer when it doesn't. Seems perfectly elegant to me. – Greg Pettit May 12 '14 at 16:59