Javascript Check if Element is in Array
In this tutorial, we cover three examples to check if an element is in an array using JavaScript. The first example uses the `includes` method, which returns a boolean value indicating whether the array contains the element or not. The second example uses the `indexOf` method, which returns the index of the element in the array, or -1 if it is not found. The third example uses a custom function that loops through the array and uses the `if-else` statement and the `===` operator to check for the element's presence.
Thanks for your feedback!
Your contributions will help us to improve service.
Example 1 : Js to check element present in array using include method
This is the first example of this tutorial. We use the JS includes method to check if an element is present in an array.
<script>
const array = [1, 2, 3, 4, 5];
const element = 3;
let outputDiv = document.getElementById('output');
function checkElement() {
if (array.includes(element)) {
outputDiv.innerHTML = 'Element is present in the array';
} else {
outputDiv.innerHTML = 'Element is not present in the array';
}
}
</script>
Example 2 : Use Js IndexOf to Check item is in Array
In this second example of this tutorial, we will use the indexOf method to check if an item is present in a JavaScript array. The indexOf method returns the index of the first occurrence of a given value in an array, or -1 if the value is not found.
<script>
const array = [3, 6, 8, 4, 5];
const element = 7;
if (array.indexOf(element) !== -1) {
console.log('Element is present in the array');
} else {
console.log('Element is not present in the array');
}
</script>
Example 3: use Loop and === Operator
In this example, we use a loop and the === operator to find if an element is present in a given array.To find an element in an array, we can use a loop to go through each element of the array and compare it with the element we are looking for using the === operator. If we find a match, we can return true. Otherwise, we can return false after the loop ends
<script>
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
const array = [2, 12, 53, 44, 15];
const element = 13;
if (contains(array, element)) {
document.write('Element is present in the array');
} else {
document.write('Element is not present in the array');
}
</script>