How to check if a value exists in an array using Javascript?

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article, we will solve for a specific case: To check if a value exists in an array.
We then also look at its implementation in Javascript and jQuery.

Where can we use this?

You might find this useful when
  • You want to execute a particular script if a certain value exists in an array
  • You want to avoid adding duplicate values to the array
If you are new to programming or quite unfamiliar with javascript, we recommend you read through the entire article, as each section of the article would be useful.

However, If you are just looking for the code, you can quickly check out the section below.

Table of Contents

Code Implementation

We are going to check for a value's existence in an array in 2 different ways using jQuery and Javascript

1) Using jQuery

If you are someone strongly committed to using the jQuery library, you can use the .inArray( ) method.

If the function finds the value, it returns the index position of the value and -1 if it doesn't.

Syntax

jQuery.inArray( search-value, array-or-string-in-which-to-search);

Code

//code to check if a value exists in an array using jQuery
<script type='text/javascript'>
var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry'];
var text = "Watermelon";
// Searching in Array
console.log( 'Index : ' + jQuery.inArray('Fig', fruits_arr) );
console.log( 'Index : ' + jQuery.inArray('Peach', fruits_arr ));

// Searching in String variable
console.log( 'Index : ' + jQuery.inArray( "m", text ));

</script>

Output

Index : 4
Index : -1
Index : 5

2) Using Javascript


Using Loop


The Idea behind it: We can check for the value we need by traversing the entire array using a looping function

<script type='text/javascript'>

//code to check if a value exists in an array using javascript for loop
var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry'];

function checkValue(value,arr){
  var status = 'Not exist';

  for(var i=0; i<arr.length; i++){
    var name = arr[i];
    if(name == value){
      status = 'Exist';
      break;
    }
  }

  return status;
}
console.log('status : ' + checkValue('Mango', fruits_arr) );
console.log('status : ' + checkValue('Peach', fruits_arr) );
</script>

Output

status : Exist
status : Not exist

Code Explanation:

From line 3 of the code, you can see that we have an array of fruits with the name fruits_arr. This contains 6 elements namely Apple, Mango, Grapes, Orange, Fig and Cherry.

The function checkValue takes 2 parameters as input, the value that needs to be searched and the array in which the value needs to be searched.

Using a for loop the function compares each element of the array with the input value you wanted to check for. If it finds a match, the function breaks and the variable status is set to Exist, else it is set to Not Exist.

Using Inbuilt function in Javascript

However, instead of writing a loop for this case, you can use the inbuilt function of Array.indexOf () for the same case. If the value exists, then the function will return the index value of the element, else it will return -1


Syntax

put-array-or-string-here.indexOf()

Code

//code to check if a value exists in an array using javascript indexOf
var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry'];

var string = "Orange";

// Find in Array
fruits_arr.indexOf('Tomato');

fruits_arr.indexOf('Grapes');

// Find in String
string.indexOf('g');

Output

-1
2
4

If you are using modern browsers you may also use the includes() function instead of the indexOf() function

If you are using modern browsers you may also use the includes() function instead of the indexOf() function

Like  indexOf() function, the includes() function also works well with primitive types.

const symbol = Symbol('symbol');

const array = [
  'hello',
  300,
  0,
  undefined,
  null,
  symbol
];

Using includes( )

//code to check if a value exists in an array using includes function
array.includes('hello'); // true
array.includes(300); // true
array.includes(0); // true
array.includes(undefined); // true
array.includes(null); // true
array.includes(symbol); // true

Using indexOf()

array.indexOf('hello') !== -1; // true
array.indexOf(300) !== -1; // true
array.indexOf(0) !== -1; // true
array.indexOf(undefined) !== -1; // true
array.indexOf(null) !== -1; // true
array.indexOf(symbol) !== -1; // true

Word of Caution


Case Sensitivity


Both includes() and indexOf()function are case sensitive

const array = ['MANGO'];
array.includes('mango'); // false
array.indexOf('mango') !== -1; // false

You can make it case insensitive by changing the case of the array

const array = ['MANGO'];

const sameCaseArray = array.map(value => value.toLowerCase());
// ['mango']

sameCaseArray.includes('mango'); // true
sameCaseArray.indexOf('mango') !== -1; // true

For a more versatile solution, you can check out using the .some() function which works well for a diverse array of data types.

Caveat of IndexOf()


One place where indexOf() and includes() differ is shown below

const array = [NaN];

// 😄
array.includes(NaN); // true

// 😞
array.indexOf(NaN) !== -1; // false

Browser Support


includes() function is not supported by IE and in that case you might want to use the indexOf() function to check if there is a value in a given array but keep in mind the caveat and limitations of the indexOf() function.

Other Related Concepts

How to remove duplicate values from a JavaScript array4 min guide

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ...

How to remove a specific item from an array in JavaScript11 min read

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ... 

Try a Top Quality Javascript Developer for 7 Days.
Pay Only If Satisfied.