How do I check if an array includes an object in JavaScript?
What is the most concise and efficient way to find out if a JavaScript array contains an object?
This is the only way I know to do it:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
Is there a better and more concise way to accomplish this?
This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using
indexOf
.Answer :
Modern browsers have
Array#indexOf
, which can do that. Even newer browsers have Array#includes
, which does exactly that, but unfortunately it's not widely supported. Older browsers can be supported using this polyfill.
jQuery offers
$.inArray
, which is functionally equivalent to Array#indexOf
.
underscore.js, a JavaScript utility library, offers
_.contains(list, value)
, alias _.include(list, value)
, both of which use indexOf internally if passed a JavaScript array.
Some other frameworks offer similar methods:
- 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_.contains
prior 4.0.0)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
Languages that compile to JavaScript
a = [1, 2, 3, 4]
alert(2 in a)
Dart:
var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);
COMMENTS