Javascript Array - indexOf method


The indexOf method searches the array until it matches your search term. It returns the index of the matched item. Notice that if there are multiple elements matching your term, it will return only the index of first match. If no match is found, it will return -1.

Take a look at the following example


<html>
<body>

<script type="text/javascript">


var cars = ["Ford", "GM","Toyota", "Honda"];
document.writeln('Index of Toyota is : ' + cars.indexOf("Toyota") + '<br />');

</script>

</body>
</html>



Try this example online here .



Useful Tips

Use the following code to find the all occurrence of an element ( See how we make intelligent use of push)

Recall that the push method adds an element at the and of the array.


var foundItems = [];
var index = array.indexOf(element)
while (index != -1)
{
  foundItems.push(index);
  index = array.indexOf(element, ++index);
} 




If you are uninitiated, ++index increments the value of the variable index.

If you are still not able to follow, here is the complete example


<html>
<body>

<script type="text/javascript">

var cars = ["Toyota","Ford", "GM","Toyota", "Honda","Toyota"];

var foundItems = [];
var index = cars.indexOf("Toyota");
while (index != -1)
{
  foundItems.push(index);
  index = cars.indexOf("Toyota", ++index);
} 

document.writeln('The Toyota occurs at positions  : ' + foundItems + '<br />');

</script>

</body>
</html>



Try this example online here .