Determine whether an array contains a value
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage
How do I check if an array includes a value in JavaScript?
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
How do I check whether an array contains a string in TypeScript?
The same as in JavaScript, using Array.prototype.indexOf():
console.log(channelArray.indexOf('three') > -1);
Or using ECMAScript 2016 Array.prototype.includes():
console.log(channelArray.includes('three'));
Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example
const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]
Reference
Array.find()
Array.some()
Array.filter()
How do I determine whether an array contains a particular value in Java?
Arrays.asList(yourArray).contains(yourValue)
Warning: this doesn't work for arrays of primitives (see the comments).
Since java-8 you can now use Streams.
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
To check whether an array of int
, double
or long
contains a value use IntStream
, DoubleStream
or LongStream
respectively.
Example
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
How to determine if Javascript array contains an object with an attribute that equals a given value?
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
Determine whether an array contains a value and update or create it
A more efficient way would be to use a proper data structure (Map
) instead of the array, for example:
let basket = new Map();
function add(product) {
if(basket.has(product.id))
basket.get(product.id).amount += product.amount;
else
basket.set(product.id, {...product});
}
add({id:1, name: 'bread', amount:1});
add({id:2, name: 'butter', amount:2});
add({id:1, name: 'bread', amount:2});
add({id:1, name: 'bread', amount:1});
console.log([...basket.values()])
Related Topics
Fastest Way to Duplicate an Array in JavaScript - Slice Vs. 'For' Loop
Origin Null Is Not Allowed by Access-Control-Allow-Origin
Build Tree Array from Flat Array in JavaScript
Is There a Standard Function to Check For Null, Undefined, or Blank Variables in JavaScript
JavaScript "New Array(N)" and "Array.Prototype.Map" Weirdness
Link and Execute External JavaScript File Hosted on Github
How to Prevent a Parent'S Onclick Event from Firing When a Child Anchor Is Clicked
Access Java/Servlet/Jsp/Jstl/El Variables in JavaScript
How to Delay the .Keyup() Handler Until the User Stops Typing
Convert Js Object to Json String
How to Get a Key in a JavaScript Object by Its Value
Convert Utc Date Time to Local Date Time
Json: Why Are Forward Slashes Escaped
How to Stop the Browser Back Button Using JavaScript
How to Convert Decimal to Hexadecimal in JavaScript
Pass an Extra Argument to a Callback Function