This article will show you how to find the index of an item in an array in JavaScript. There are several approaches to find the index of an item in an array in JavaScript, each with a description and complete code example are given below:
1. Using indexOf() Method
Using the indexOf()
method to find the first index of a specified item in the array.
const array = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; const indexOfItem = array.indexOf(itemToFind); // Output: 1 console.log(indexOfItem);
2. Using indexOf() with fromIndex
Using the indexOf()
method with a specified starting index to find subsequent occurrences.
const array = ['Apple', 'Banana', 'Orange', 'Banana']; const itemToFind = 'Banana'; const indexOfItem = array.indexOf(itemToFind, 1); // Output: 1 console.log(indexOfItem);
3. Using findIndex() Method
Using the findIndex()
method to find the index based on a provided condition.
const array = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; const indexOfItem = array.findIndex(item => item === itemToFind); // Output: 1 console.log(indexOfItem);
4. Using for Loop
Using a traditional for
loop to iterate over the array and find the index.
const array = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; let indexOfItem = -1; for (let i = 0; i < array.length; i++) { if (array[i] === itemToFind) { indexOfItem = i; break; } } // Output: 1 console.log(indexOfItem);
5. Using Array.indexOf() in a Function
Creating a function that uses indexOf()
to find the index of an item.
function findIndex(array, item) { return array.indexOf(item); } const fruits = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; const indexOfItem = findIndex(fruits, itemToFind); // Output: 1 console.log(indexOfItem);
6. Using Array.findIndex() in a Function
Creating a function that uses findIndex()
to find the index based on a condition.
function findIndexByCondition(array, condition) { return array.findIndex(condition); } const fruits = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; const indexOfItem = findIndexByCondition(fruits, item => item === itemToFind); // Output: 1 console.log(indexOfItem);
7. Using Array.includes() and indexOf() Methods
Using includes()
to check if the item exists and indexOf()
to get the index.
const array = ['Apple', 'Banana', 'Orange']; const itemToFind = 'Banana'; const indexOfItem = array.includes(itemToFind) ? array.indexOf(itemToFind) : -1; // Output: 1 console.log(indexOfItem);