Get index or position of a JavaScript array item

Each javaScript array item has an index number that tells us the position of that item in that array. Here in this task, we are going to take a JavaScript array and then find the index of a particular element to get the position of that item.

Before we go through, first we need to take an array. After that, we will perform our simple operation to get the position of the specific element in from the array. It can be done just by using simple javaScript code and an in-built method.

See the complete code example below to get and show the result in the console log:

var animals = ["Cat", "Dog", "Donkey", "Monkey", "Cow", "Goat"];
var arrIndex = animals.indexOf("Monkey");

In the above example, we are able to do our task successfully. First of all, we take an array and assigned it inside the variable animals. As you can see, the array contains some animal names as items. From the items, we find the index number of “Monkey” to get the position.

As you can see, we have used the indexOf() JavaScript method. This method is responsible to do our job. The JS indexOf() method is searching the array for a particular item and then returns its position. We are simply passing the item of the array for which we want to get the index number. In the end, we show it in the console.log

That’s it. So easy… I hope, you have learned something new in a simple way from this article.

Leave a Reply

Your email address will not be published. Required fields are marked *