Open In App

Find the Array Index with a Value in JavaScript

We have a given value and we need to find out whether the given is present in the array or not, If it is present then we have to print the index number of that existing value, and if it is not present then we will print -1.



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:



Using indexOf() method

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

Using findIndex() method

Example : This example is the implementation of the above-explained approach.




const array = [10, 20, 30, 40];
const index = array.findIndex(num => num > 25);
console.log(index); // Output: 2

Output
2

Using for loop

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

Using Lodash _.findIndex() Method

Example: This example is the implementation of the above-explained approach.




// Requiring the lodash library
const _ = require('lodash');
 
// Original array
let array1 = [4, 2, 3, 1, 4, 2]
 
// Using lodash.findIndex
let index = _.findIndex(array1, (e) => {
    return e == 1;
}, 0);
 
// Print original Array
console.log("original Array: ", array1)
 
// Printing the index
console.log("index: ", index)

Output:

original Array: [ 4, 2, 3, 1, 4, 2]
index: 3

Article Tags :