How to use for loop In Javascript
- Another approach to finding the index of an array with a specific value is to use a for loop to iterate through the array and compare each element with the value.
- The loop iterates through each element of the numbers array and checks if the current element is equal to 30.
- When element 30 is found at index 2, the loop is terminated using the break statement, and index 2 is stored in the index variable.
- Finally, the index variable is logged to the console, which outputs 2.
Example : This example is the implementation of the above-explained approach.
const arraynumbers = [10, 20, 30, 40];
let index = -1;
for (let i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] === 30) {
index = i;
break;
}
}
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