The indexOf()
method searches an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
Example
Search an array for the item "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
let position = fruits.indexOf("Apple") + 1;
Array.indexOf()
is supported in all browsers except Internet Explorer 8 or earlier.
Syntax
array.indexOf(item, start)item | Required. The item to search for. |
start | Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end. |
Array.indexOf()
returns -1 if the item is not found.
If the item is present more than once, it returns the position of the first occurrence.
Practice Excercise Practice now