The indexOf method in JavaScript
If you are working with arrays in JavaScript, particularly with large arrays, there may be a scenario to find only the specific array element to accomplish a certain task.
The indexOf method, as the name shows, is used to search the index of an array element.
const fruits_arr = ['apple', 'mango', 'orange']; const search_Index = fruits_arr.indexOf('mango'); // Result will be 1
- It tells whether the array contains the given element or not.
- If the given element in indexOf method is found, it will return the index number of that element.
- Otherwise, the indexOf returns the -1 value.
Syntax
This is how you may use the indexOf method in JavaScript:
var search_element = Array.indexOf(element, starting_index);
The indexOf method accepts two parameters.
Parameters | Description |
element | The first is the element to check if the given array contains it or not. |
starting_index |
|
I will explain it further with an online demonstration, let me start with a simple example first.
A simple example of using indexOf JavaScript method
In this example, a simple array of five numeric elements is created.
As you click the button, the indexOf method will execute where the index of element “2” will be searched and shown in an alert.
Code:
<!doctype html> <html> <head> <style> #arr_indexof { background: #415665; height: auto; width:300px; border-radius: 15px; padding:20px; font-size:22px; color:#fff; } .btncls{ background-color:#4B4FC5; border: #2e6da4; font-family: Arial, Geneva, Arial, Helvetica, sans-serif; font-size: 15px; color: #FFFFFF; letter-spacing: 1px; padding: 8px 12px; font-size: 14px; font-weight: normal; border-radius: 4px; line-height: 1.5; text-decoration:none; } </style> </head> <body> <div id="arr_indexof"></div> <p><button class="btncls" onclick="elementexists()">Index of element "2"</button></p> <script> var arr_indexof = [1,2,3,4,5]; var i; var j= 10; // Used to give values to array elements var num; var initialArray = "The array elements <BR><BR>"; for (num=0; num < arr_indexof.length; num++){ initialArray += arr_indexof[num] + "<BR>"; } document.getElementById("arr_indexof").innerHTML = initialArray; function elementexists(){ var ele_index = arr_indexof.indexOf(2); alert (ele_index); } </script> </body> </html>
Output:
The alert shows “1” as the index number of the element. The following function of JS is executed on the click event of the button:
function elementexists(){ var ele_index = arr_indexof.indexOf(2); alert (ele_index); }
An example if an array does not contain the searched element
In this example, an element is given in indexOf method that does not exist in the specified array. The same array is used as in the above example.
Code:
<body> <div id="arr_indexof"></div> <p><button class="btncls" onclick="elementexists()">Index of element "6"</button></p> <script> var arr_indexof = [1,2,3,4,5]; var i; var j= 10; // Used to give values to array elements var num; var initialArray = "The array elements <BR><BR>"; for (num=0; num < arr_indexof.length; num++){ initialArray += arr_indexof[num] + "<BR>"; } document.getElementById("arr_indexof").innerHTML = initialArray; function elementexists(){ var ele_index = arr_indexof.indexOf(6); alert ("Index of element 6 = " + ele_index); } </script> </body>
Output as button is clicked:
You see, I used element “6” to check whether the given array contains it or not. As this element does not exist, it returned -1.
You may perform a certain action based on this value e.g. showing the user a message that “a given search term does not exist”.
An example of specifying the starting index
To demonstrate the starting index parameter, an array is created with six elements.
The element which is specified in the JavaScript indexOf method exists twice.
First, have a look at the output without using the start_index parameter. The array is:
<!doctype html> <html> <head> <style> #arr_indexof { background: #804040; height: auto; width:300px; border-radius: 15px; padding:20px; font-size:22px; color:#fff; } .btncls{ background-color:#FF0000; border: #2e6da4; font-family: Arial, Geneva, Arial, Helvetica, sans-serif; font-size: 15px; color: #FFFFFF; letter-spacing: 1px; padding: 8px 12px; font-size: 14px; font-weight: normal; border-radius: 4px; line-height: 1.5; text-decoration:none; } </style> </head> <body> <div id="arr_indexof"></div> <p><button class="btncls" onclick="elementexists()">Index of element "1"</button></p> <script> var arr_indexof = [1,2,3,4,5,1,6]; var i; var j= 10; // Used to give values to array elements var num; var initialArray = "The array elements <BR><BR>"; for (num=0; num < arr_indexof.length; num++){ initialArray += arr_indexof[num] + "<BR>"; } document.getElementById("arr_indexof").innerHTML = initialArray; function elementexists(){ var ele_index = arr_indexof.indexOf(1); alert ("Index of element 1 = " + ele_index); } </script> </body> </html>
Output:
Now, have a look at the output as I specified the starting index 3 in the indexOf method.
<body> <div id="arr_indexof"></div> <p><button class="btncls" onclick="elementexists()">Index of element "1"</button></p> <script> var arr_indexof = [1,2,3,4,5,1,6]; var i; var j= 10; // Used to give values to array elements var num; var initialArray = "The array elements <BR><BR>"; for (num=0; num < arr_indexof.length; num++){ initialArray += arr_indexof[num] + "<BR>"; } document.getElementById("arr_indexof").innerHTML = initialArray; function elementexists(){ var ele_index = arr_indexof.indexOf(1,3); alert ("Index of element 1 = " + ele_index); } </script> </body>
Output:
This is how the indexOf method is used in above example with start index:
var ele_index = arr_indexof.indexOf(1,3);
It started searching for the element “1” from index 3. So the first occurrence at position 0 was ignored and the alert is showing “5”, which is the second occurrence.
An example of searching array of strings
- In this example, an array of US state names is created. After selecting a State name from the dropdown, click on the button to see if that State name is contained in that array or not.
- Upon clicking the button, the indexOf array method will execute that will search the user-selected State name, and return a value.
- If the State name is found, it will be index number, otherwise, it will return -1.
Code:
<!doctype html> <html> <head> <style> #arr_indexof { background: #9D9D00; height: auto; width:300px; border-radius: 15px; padding:20px; font-size:22px; color:#fff; } .btncls{ background-color:#008000; border: #2e6da4; font-family: Arial, Geneva, Arial, Helvetica, sans-serif; font-size: 15px; color: #FFFFFF; letter-spacing: 1px; padding: 8px 12px; font-size: 14px; font-weight: normal; border-radius: 4px; line-height: 1.5; text-decoration:none; } </style> </head> <body> <div id="arr_indexof"><label>Select a State:</label> <select id="selectstate"> <option>Alaska</option> <option>California</option> <option>Florida</option> <option>Texas</option> <option>New York</option> <option>Hawaii</option> </select> <p><button class="btncls" onclick="elementexists()">Check if exist in array</button></p> </div> <script> function elementexists(){ var selectedState = document.getElementById("selectstate").value; var USStates = ["New York", "Texas", "Florida","Alaska"]; var arrsearch; arrsearch = USStates.indexOf(selectedState); if (arrsearch != -1){ alert ("The State exist in Array and its index is: " +arrsearch); } else{ alert("The State does not exist in array!"); } } </script> </body> </html>
Output:
You saw the alert is showing a more descriptive message if the State exists or not. This is how the indexOf method is used in the demo:
function elementexists(){ var selectedState = document.getElementById("selectstate").value; var USStates = ["New York", "Texas", "Florida","Alaska"]; var arrsearch; arrsearch = USStates.indexOf(selectedState); if (arrsearch != -1){ alert ("The State exist in Array and its index is: " +arrsearch); } else{ alert("The State does not exist in array!"); } }
An example of using the lastIndexOf method
In the above examples, the element search started from the 0 index i.e. start of an array by using the indexOf method.
See the following example, where I am using the same array as created in the above example; with repeated elements.
The occurrence of element “1” is twice, however, the lastIndexOf method is used.
See the output and difference between the two methods:
This is how the lastIndexOf method is used in the example:
function elementexists(){ var ele_index = arr_indexof.lastIndexOf(1); alert ("Index of element 1 = " + ele_index); }
You see, the element “1” is present at 0 and 5 indexes.
However, the lastIndexOf searched from the last i.e. 5, unlike the indexOf method that returned 0.