Can someone tell me how to detect if "specialword" appears in an array? Example:
categories: [
"specialword"
"word1"
"word2"
]
-
In pure JS: stackoverflow.com/a/25765186/1320932dr.dimitru– dr.dimitru2014年09月10日 12:19:17 +00:00Commented Sep 10, 2014 at 12:19
-
37pure JS : categories.includes("specialword")patz– patz2016年04月12日 17:50:46 +00:00Commented Apr 12, 2016 at 17:50
-
4@patz watch out for pure JS, not supported in IE (any version) linkfoxontherock– foxontherock2017年12月12日 15:29:56 +00:00Commented Dec 12, 2017 at 15:29
-
@foxontherock start using transpiler - stop worrying about anything fact-checking, can-I-use-this-property kinda thing.Alex Pogiba– Alex Pogiba2018年08月23日 06:52:27 +00:00Commented Aug 23, 2018 at 6:52
-
Does this answer your question? How do I check if an array includes a value in JavaScript?gre_gor– gre_gor2023年05月03日 18:20:50 +00:00Commented May 3, 2023 at 18:20
7 Answers 7
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.
6 Comments
'foo' in arr?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.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():
const 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.
const categoriesPresent = ['word', 'word', 'specialword', 'word'];
const categoriesNotPresent = ['word', 'word', 'word'];
const foundPresent = categoriesPresent.includes('specialword');
const foundNotPresent = categoriesNotPresent.includes('specialword');
console.log(foundPresent, foundNotPresent); // true false
Comments
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
}
Comments
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.
1 Comment
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;
}
}
4 Comments
const found = categories.any(c => c === "specialword");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; }
Comments
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);
}