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

JavascriptObject Oriented ProgrammingProgramming

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

 Live Demo

<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

 Live Demo

<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
raja
Published on 20-May-2019 15:21:13
Advertisements