How do I check if an array includes a value in JavaScript?

How do I check if an array includes a value in JavaScript?
How do I check if an array includes a value in JavaScript?

In JavaScript, you can use the Array.prototype.includes() method to check if an array includes a specific value.

Here’s an example of how you can use the includes() method to check if an array of numbers includes the number 42:

var numbers = [1, 2, 3, 42, 5];
console.log(numbers.includes(42));  // output: true

The includes() method returns a boolean value indicating whether the specified value is found in the array. In the above example, since 42 is present in the array the output is true.

You can also check if the array includes an object in the array

var people = [{name:'John',age:40}, {name:'Mike',age:25}, {name:'Bob',age:35}];
console.log(people.includes({name:'Bob',age:35}));  // output: false

It will return false because it compares object reference not the object values.

In this case, you can use Array.prototype.find() method to find the desired object by key-value match

console.log(people.find(person => person.name === 'Bob' && person.age === 35));

This method returns the first element in the array that satisfies the provided testing function; otherwise, undefined is returned.

You can also use indexOf() method to check if a value exists in an array or not.

console.log(people.indexOf({name:'Bob',age:35}) != -1)

It returns the first index at which a given element can be found in the array, or -1 if it is not present.

Leave a Reply