Find the first index of "Apple":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.indexOf("Apple");
Start at index 3:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", 3);
More examples below.
DescriptionThe indexOf()
method returns the first index (position) of a specified value.
The indexOf()
method returns -1 if the value is not found.
The indexOf()
method starts at a specified index and searches from left to right (from the given start postion to the end of the array).
By default the search starts at the first element and ends at the last.
Negative start values counts from the last element (but still searches from left to right).
Array Find Methods: Method Finds includes() Returns true if an array contains a specified value indexOf() The index of the first element with a specified value lastIndexOf() The index of the last element with a specified value find() The value of the first element that passes a test findIndex() The index of the first element that passes a test findLast() The value of the last element that passes a test findLastIndex() The index of the last element that passes a test Syntaxarray.indexOf(item, start)
Parameters Parameter Description item Required.In an array, the first element has index (position) 0, the second has index 1, ...
More ExamplesFind the first index of "Apple", starting from the last element:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
let index = fruits.indexOf("Apple", -1);
indexOf()
is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
ChromeTrack your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4