How to use Array.prototype.findIndex() method In Javascript
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
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
Contact Us