In this guide, we are going to show you how to check if a certain value exists in a JavaScript array.
This can be useful if you want to avoid adding duplicate items to an array.
You can also use it for client-side searches.
Take a look at the following function:
/** * JavaScript function that checks to see whether an array * contains a certain value. * @param arr The array you want to search. * @param searchFor The value you want to search for. * @returns {boolean} TRUE if the value exists in the array. FALSE otherwise. */ function arrayContains(arr, searchFor){ if(typeof arr.includes == 'undefined'){ var arrLength = arr.length; for (var i = 0; i < arrLength; i++) { if (arr[i] === searchFor) { return true; } } return false; } return arr.includes(searchFor); }
In the code above, we created a custom JavaScript function called arrayContains.
This function takes two parameters: The array that you want to search and the value that you want to search for.
If the value you’re searching for exists in the array, then this function will return a boolean TRUE value. Otherwise, it will return FALSE.
At the start of our function, we check to see if the inbuilt Array.prototype.includes() method exists. If it does not exist, then we loop through the array manually and check if the element exists.
We added this “typeof” check in order to provide some sort of backwards compatibility for older browsers.
However, it is unlikely that this code block will execute. This is because almost all modern web browsers support JavaScript’s includes() method.
It is important to note that both the includes() method and the manual search in this custom function are case-sensitive.
Take a look at the following examples:
//An example JavaScript array. var myArray = new Array( 'John', 'Sarah', 'Lee', 'Aarav', 'Miguel' ); console.log(arrayContains(myArray, 'Lee')); //returns true console.log(arrayContains(myArray, 'lee')); //returns false console.log(arrayContains(myArray, 'Patrick')); //returns false
In this code snippet, “lee” returns false because of the lowercase L.
“Patrick” also returns false because that string does not exist in the array.
Using jQuery to check if a value exists in a JavaScript array.
If you are already using the jQuery library, then you can simply use the inArray() method like so:
//Using the JQuery inArray method if(jQuery.inArray("Sarah", myArray) !== -1){ console.log('Sarah found in array.'); }
The $.inArray() method will return a -1 value if the item does not exist inside the array. Unlike the function in our first example, it does not return any boolean values.
If the value does exist inside the array, then $.inArray() will not return -1. Hence the reason we check to see if the return value is -1 or not.
Note that this method carries out a strict comparison. In other words, it is also case-sensitive.