Determine Whether an Array Contains a Value

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



Leave a reply



Submit