Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); // true
You can also use Array#indexOf, which is less direct, but doesn't require polyfills for outdated browsers.
console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); // true
Many frameworks also offer similar methods:
- jQuery:
$.inArray(value, array, [fromIndex]) - Underscore.js:
_.contains(array, value)(also aliased as_.includeand_.includes) - Dojo Toolkit:
dojo.indexOf(array, value, [fromIndex, findLast]) - Prototype:
array.indexOf(value) - MooTools:
array.indexOf(value) - MochiKit:
findValue(array, value) - MS Ajax:
array.indexOf(value) - Ext:
Ext.Array.contains(array, value) - Lodash:
_.includes(array, value, [from])(is_.containsprior 4.0.0) - Ramda:
R.includes(value, array)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
What is the correct situation to use array.find() vs. array.includes vs. array.some() ?
Includes vs. In
JavaScript - include() - A check to see if multiple elements are in an array - Stack Overflow
(Silly?) inferencing issue/question for Array.includes()
Videos
Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); // true
You can also use Array#indexOf, which is less direct, but doesn't require polyfills for outdated browsers.
console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); // true
Many frameworks also offer similar methods:
- jQuery:
$.inArray(value, array, [fromIndex]) - Underscore.js:
_.contains(array, value)(also aliased as_.includeand_.includes) - Dojo Toolkit:
dojo.indexOf(array, value, [fromIndex, findLast]) - Prototype:
array.indexOf(value) - MooTools:
array.indexOf(value) - MochiKit:
findValue(array, value) - MS Ajax:
array.indexOf(value) - Ext:
Ext.Array.contains(array, value) - Lodash:
_.includes(array, value, [from])(is_.containsprior 4.0.0) - Ramda:
R.includes(value, array)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.
As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
Of course, you may as well extend Array prototype:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
And now you can simply use the following:
alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false
I understand how each of these methods work, but they all seem to have similar functions to one another, and I'm not sure as to what situation might call for what method.
ยป npm install array-includes
The issue is in your if statement because includes() returns a boolean based on the string parameter. A better way of doing this would be to use something like:
if(arr.includes("TL") && arr.includes("TM") && arr.includes("TR")) {
console.log("yes");
}
If you have lots of elements in your array I would suggest something more along the lines of:
var flag = true;
for(i=0; i<arr.length; i++) {
if(!arr.includes(arr[i])) {
flag = false;
}
}
if(flag) {
console.log("yes");
}
This can be done cleanly using the reduce method of arrays. Here's how to do it with your example:
var arr = ["TL", "TM", "TR"];
var fails = ["TL"] // This will return false
var succeeds = ["TL", "TM", "TR"] // This will return true
var includesAll = (array_to_check) => arr.reduce(
(accumulator, current) => accumulator && array_to_check.includes(current),
true
)
if (includesAll(succeeds)){
console.log("yes");
} else {
console.log("nope");
}
Usually Typescript is pretty good at looking at mutually exclusive branches and deduce the types of variables when there are multiple options, so I'm embarrassed to even ask this, but here goes nothing.
We have two variables which will serve as an array of stuff, and a value to look for, using the native includes() function for arrays. We will either have an array of strings and search for a string, or an array of integers and search for an integer. We will not have a mixed array of strings and/or integers, and wouldn't like to loosen this definition with Array<string | number> to accommodate incorrect inferencing.
If we just declare the two variables without any branching typescript correctly infers they are of matching types and the function will run just fine, since it's defined as includes(searchElement: T, fromIndex?: number): boolean; for Array<T>
However, once it goes through branching logic, it stops being able to make this inference... here's a naive example of what I'm talking about: Playground link
I must be missing something here!