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:
Notice that some frameworks implement this as a function, while others add the function to the array prototype.

Commentaires

Posts les plus consultés de ce blog

How to start old power supplies from PC