JavaScript – Find Index of an Element in Array

To find index of a given element in array in JavaScript, call indexOf() method on this array and pass the element to find as argument to this indexOf() method.

Example

In the following example, we have taken an array in inputArr, and element in e. We find the index of element e in the array inputArr using indexOf() method.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <pre id="output"></pre>
    <script>
        var inputArr = ['banana', 'mango', 'apple'];
        displayOutput = 'Input Array : ' + inputArr;

        var e = 'mango';
        var index = inputArr.indexOf(e);
        displayOutput += '\nIndex of '+ e +' : ' + index;

        document.getElementById("output").innerHTML = displayOutput;
    </script>
</body>
</html>

indexOf() method returns the first occurrence of the element in this array.

Conclusion

In this JavaScript Tutorial, we learned how to find the index of an element in an array using indexOf() method.