JavaScript Find Index of a Value in Array (original) (raw)

Last Updated : 18 Nov, 2024

Here are some effective methods to find the array index with a value in JavaScript.

Using indexOf() - Most Used

indexOf() returns the first index of a specified value in an array, or -1 if the value is not found.

JavaScript `

const a = [10, 20, 30, 40, 50];

// Find index of value 30 const index = a.indexOf(30); console.log(index);

// Value not found const notFound = a.indexOf(60); console.log(notFound);

`

Using findIndex() for Complex Conditions

findIndex() is used for finding the index of an element based on complex conditions. It takes a callback function that can include any logic for locating an item within the array.

JavaScript `

const a = [10, 15, 20, 25, 30];

// Find index of first value greater than 18 const index = a.findIndex(value => value > 18); console.log(index);

`

Using a for loop gives you complete control over how you search for items. You can stop the loop as soon as you find what you’re looking for, making it a flexible option for setting custom rules.

JavaScript `

const a = [5, 10, 15, 20, 25]; let index = -1;

// Find index of value 20 for (let i = 0; i < a.length; i++) { if (a[i] === 20) { index = i; break; } } console.log(index);

`

If you need the last occurrence of a value you can use lastIndexOf() method which returns the index of the last match, or -1 if the value is not found. This is useful what an arrays contain duplicate values.

JavaScript `

const a = [5, 10, 15, 10, 5];

// Find last index of value 10 const index = a.lastIndexOf(10); console.log(index);

`

Importance of Finding Array Indices

Finding array indices is essential for

Find the Array Index with a Value in JavaScript