Find the index of an element in a JavaScript array by value

Last updated: April 15, 2022.

If you are looking to find the index of an array element at its first or last appearance in an array, you have it relatively easy in JavaScript.

To find the index value of the first instance of an element’s occurrence, you can use the indexOf array method. Just passing in the element value you are searching for:

/* Find index value of first instance of element */

const animals = ["🐶","🐱","🐭","🐹","🐰","🦊"];

animals.indexOf("🐶"); // 0  (JS starts counting from 0)
animals.indexOf("🐰"); // 4
animals.indexOf("🐻"); // -1 (not found)

To find the index of the last appearance of an element, you can use lastIndexOf in the same way:

/* Find index value of last instance of element */

const animals = ["🐶","🐶","🐶","🐹","🦊","🦊", "🐹"];

animals.lastIndexOf("🐶"); // 2
animals.lastIndexOf("🦊"); // 5
animals.lastIndexOf("🐭"): // -1 (not found)

But what about the second, third or fourth index of an element? Or the index of all appearances on an element?

You can create a loop for this purpose. The loop takes advantage of an option second parameter in the indexOf method: the index in the array from which to start the search.

The loop keeps pushing found indexes of the element into an array (finds) until an index search returns -1, indicating that there are no more indexes for the element in the array:

/* Function that returns index values of all instances of an element */

function getIndexes(element, array) {
    const finds = [];
    let index = array.indexOf(element); // gets first index

    while (index !== -1) { // loop breaks when index is -1 (no index found)
        finds.push(index); // pushes indexes into finds
        index = array.indexOf(element, index + 1); // Sets index to most recent index find + 1
    return finds;

/* Basic usage */

const animals = ["🐶","🐶","🐶","🐹","🦊","🦊", "🐹"];

getIndexes("🐹", animals); // [3, 6]
getIndexes("🐶", animals); // [0, 1, 2]
getIndexes("🐻", animals); // []

As you can see, this returns every index position at which an element appears. So to get the nth appearance of an element, all you have to do is query this result:

/* Using the function to return the index value of a specific instance of an element */

getIndexes("🦊", animals)[1] // 5
getIndexes("🐶", animals)[2] // 2
getIndexes("🐻", animals)[2] // undefined