How to use indexOf() method In Javascript
- We have an array of fruits and want to find the index of the element ‘cherry’.
- We use the indexOf() method to search for ‘cherry’ in the fruits array and it returns the index of ‘cherry’, which is 2.
Example: This example is the implementation of the above-explained approach.
const fruits = ['apple', 'banana', 'cherry', 'orange'];
const index = fruits.indexOf('cherry');
console.log(index); // Output: 2
Output
2
Find the Array Index with a Value in JavaScript
Finding the index of a specific value in an array in JavaScript involves searching through the array’s elements to locate the position of the desired value. This index serves as a reference point for accessing or manipulating the value within the array.
Example 1:
Input: ['apple', 'banana', 'cherry', 'orange']
N = 'cherry'
Output: 2
Explanation: The index of the word cherry is 2
These are the following approaches by using these we can find the Array Index with a Value:
Table of Content
- Using indexOf() method
- Using findIndex() method
- Using for loop
- Using Lodash _.findIndex() Method
- Using reduce method