How to Check if an Element Exists in an Array in JavaScript?
Given an array, the task is to check whether an element present in an array or not in JavaScript. If the element present in array, then it returns true, otherwise returns false.
The indexOf() method returns the index of first occurance of element in an array, and -1 of the element not found in array.
Syntax
let isExist = array.indexOf(element) !== -1;
const array = [1, 2, 3, 4, 5];
const element = 3;
const isExist = array.indexOf(element) !== -1;
console.log(isExist);
Output
true
Please Read JavaScript Array Tutorial for complete understanding of JavaScript Array.
Table of Content
Using includes() Method
The includes() method returns a boolean value indicating whether an array includes a certain value among its entries or not.
const array = [1, 2, 3, 4, 5];
const element = 3;
let isExist = array.includes( element );
console.log(isExist);
Output
true
Using find() Method
The find() method returns the value of the first element in the array that satisfies the provided testing function.
const array = [ 1, 2, 3, 4, 5 ];
const element = 3;
let isExist = array.find(item => item === element) !== undefined;
console.log( isExist );
Output
true
Using some() Method
The some()method tests whether at least one element in the array passes the test condition by the provided function.
const array = [ 1, 2, 3, 4, 5 ];
const element = 3;
const isExist = array.some(item => item === element);
console.log(isExist);
Output
true
Using Array findIndex() Method
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
const array = [ 1, 2, 3, 4, 5 ];
const element = 3;
const isExist = array.findIndex(item => item === element) !== -1;
console.log(isExist);
Output
true
Using for Loop (Brute Force Approach)
This approach iterates over each element of the array and checks if it matches the target element. If a match is found, it returns true; otherwise, it returns false.
const array = [ 1, 2, 3, 4, 5 ];
const element = 3;
let isExist = false;
for( let i = 0; i < array.length; i++ ) {
if( array[i] === element ) {
isExist = true;
break;
}
}
console.log(isExist);
Output
true