Array.prototype.indexOf
Finds a value in an array and returns its index.
Available since: ES5
Syntax
array.indexOf(searchElement, fromIndex)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchElement | any | The value to find. |
| fromIndex | number | Optional. The position to start searching from. From the beginning by default. |
Return value
numberThe index of the first match, or -1.
Examples
The position of an element:
const colors = ['red', 'green', 'blue'];
console.log(colors.indexOf('green'));
console.log(colors.indexOf('pink'));Output:
1
-1Removing an element by value:
const colors = ['red', 'green', 'blue'];
const index = colors.indexOf('green');
if (index !== -1) {
colors.splice(index, 1);
}
console.log(colors.join(', '));Output:
red, blueNotes
The comparison is strict, like ===, so [NaN].indexOf(NaN) gives -1 and objects are found only by reference. To find an object by a property use findIndex().
See also
- Array.prototype.includes — Checks whether an array contains a value.
- Array.prototype.findIndex — Returns the index of the first element that passes a test.
- Array.prototype.lastIndexOf — Finds a value from the end of an array and returns its index.
Related recipes
In the tutorial
- Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.