JavaScript Check if an Array Contains a Value

JavaScript includes() method; In this tutorial, i am going to show you how to checks whether the javascript array contains the specified element or not using the includes() method on the array instance.

How to Check if an Array Contains a Value in JavaScript

Using the javaScript includes() method, you can if an array contains value or not.

The javaScript includes method returns true if an array contains a given element; Otherwise, it returns false.

Syntax of javaScript includes() method

The following illustrates the syntax of the includes() method:

array.includes(element,fromIndex);Code language: CSS (css)

The includes() accepts two arguments:

  • The first argument is the element that can be searched.
  • The fromIndex is the position in the array to which the search starts.

Example 1 – To Check if an Array Contains a Value in JavaScript

Here, i will take an example for check if an array contains a value in javascript; as shown below:

See the following example:

[1,2,3].includes(2); // true
[1,2,3].includes(4); // false
[1,2,3].includes(1,1); // false

Both methods indexOf() method and the includes() method works absolutely fine with the NaN:

[NaN].includes(NaN); // true

Note that the includes() doesn’t differentiate between +0 and -0. See the following example:

[-0].includes(+0); // true

The following example demonstrates how to use the includes() method to check if an object is in an array.

let php = {name: 'PHP' }, 
    java = { name: 'JAVA'},
    c = {name: 'C'}
let lang = [java, c];
console.log(lang.includes(java)); // true
console.log(lang.includes(php)); // false

In this example:

  • First, we initialized the lang array with three objects:  javaand c.
  • Then, we used the includes() method to check if the lang array contains the  java object, in this case, it returns true.
  • Finally, the  php object is not in the  lang array, therefore, the includes() method returns true as expected.

Examples 2 – To Check if an Array Contains a Value in using Javascript IndexOf()

Here, i will take an example for check if the array contains an element. As shown below:

let numbers = [3,4,5,6,7,8];
if(numbers.indexOf(5) !== -1){
   // process here

Conclusion

In this tutorial, you have learned how to use the JavaScript Array includes() method to determines whether an array contains a specified element.

More javaScript Tutorial

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published.