How do I check if an array includes an object in JavaScript? -
what concise , efficient way find out if javascript array contains object?
this way know it:
function contains(a, obj) { (var = 0; < a.length; i++) { if (a[i] === obj) { return true; } } return false; }
is there better , more concise way accomplish this?
this closely related stack overflow question best way find item in javascript array? addresses finding objects in array using indexof
.
current browsers have array#includes
, exactly that, is supported, , has polyfill older browsers.
you can use array#indexof
, less direct, doesn't require polyfills out of date browsers.
jquery offers $.inarray
, functionally equivalent array#indexof
.
underscore.js, javascript utility library, offers _.contains(list, value)
, alias _.include(list, value)
, both of use indexof internally if passed 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) - ecmascript 2016:
array.includes(value)
notice frameworks implement function, while others add function array prototype.
Comments
Post a Comment