Computer >> Computer tutorials >  >> Programming >> Javascript

Write a program to find the index of particular element in an array in javascript?


indexOf()

To find the index of any element , indexOf() method is used .The following example gives the index of a particular element(solarCity) from a given array.

Example

<html>
<body>
<p id="index"></p>
<script>
   var companies = ["Spacex", "Tesla", "SolarCity", "Neuralika"];
   var res = companies.indexOf("SolarCity");
   document.getElementById("index").innerHTML = res;
</script>
</body>
</html>

Output

2

 

This method also helps to find the index of an element after a given specified index.The following example searches index of a particular element " solarCity" not from starting but from the given specified index 4.Therefore the index is 6 but not 2.

Example

<html>
<body>
<p id="index"></p>
<script>
   var companies = ["Spacex", "Tesla", "SolarCity", "Neuralika", "Spacex",
                    "Tesla", "SolarCity", "Neuralika"];
   var res = companies.indexOf("SolarCity", 4);
   document.getElementById("index").innerHTML = res;
</script>
</body>
</html>

Output

6