How to Check if an Element Exists in an Array in JavaScript ?
In JavaScript, you can check if an element exists in an array using various methods, such as indexOf()
, includes()
, find()
, some()
, or Array.prototype.findIndex()
.
Here’s how you can achieve it using these methods:
Table of Content
- Using indexOf() method
- Using includes() method
- Using find() method
- Using some() method
- Using Array.prototype.findIndex() method
Using indexOf() method
The indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const array = [1, 2, 3, 4, 5];
const element = 3;
// Checks if element exists
const exists = array.indexOf(element) !== -1;
console.log(exists); // Output: true
Using includes() method
The includes()
method returns a boolean indicating whether an array includes a certain value among its entries.
const array = [1, 2, 3, 4, 5];
const element = 3;
// Checks if element exists
const exists = array.includes(element);
console.log(exists); // 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;
// Checks if element exists
const exists = array.find(item => item === element) !== undefined;
console.log(exists); // Output: true
Using some() method
The some()
method tests whether at least one element in the array passes the test implemented by the provided function.
const array = [1, 2, 3, 4, 5];
const element = 3;
// Checks if element exists
const exists = array.some(item => item === element);
console.log(exists); // Output: true
Using Array.prototype.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;
// Checks if element exists
const exists = array.findIndex(item => item === element) !== -1;
console.log(exists); // Output: true
Contact Us