How to use findIndex() with includes() In Javascript
We can use the findIndex() method with the includes() method to directly search for the substring in the array and return the index of the same.
Syntax:
array.findIndex(element => element.includes(substring))
Example: The below code example finds the index of an element that contains the given substring in an array.
Javascript
const array = [ 'apple' , 'banana' , 'orange' , 'grape' ]; const substring = 'an' ; const index = array.findIndex (element => element.includes(substring)); console.log( "The first appearence of the given substring " + "found in the element present at index" , index); |
Output
The first appearence of the given substring found in the element present at index 1
How to Find the Index of an Element that Contains the Given Substring in Array ?
To find the index of an element within an array that contains a specific substring in JavaScript, there are multiple strategies available. The methods offer flexibility in handling various scenarios, allowing you to efficiently locate the index of the desired substring within the array.
Table of Content
- Using findIndex() with includes()
- Using findIndex() with indexOf()
- Using a loop
Contact Us