How do I check if an array includes an object in JavaScript?
Similar thing: Finds the first element by a "search lambda":
Array.prototype.find = function(search_lambda) {
return this[this.map(search_lambda).indexOf(true)];
};
Usage:
[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4
Same in coffeescript:
Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]
Current browsers have
Array#includes, which does exactly that, is widely supported, and has a polyfill for older browsers.
You can also use
Array#indexOf, which is less direct, but doesn't require Polyfills for out of date browsers.
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_.containsprior 4.0.0) - ECMAScript 2016:
array.includes(value)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
Commentaires
Enregistrer un commentaire