indexOf()
indexOf<
T>(array,value,fromIndex?):number
Gets the index at which the first occurrence of value is found in array.
DEPRECATED
Use array.indexOf(value) directly instead.
Reason:
Native equivalent method now available
Type Parameters
T: T
The type of elements in the array.
Parameters
array: T[]
The array to search.
value: T
The value to search for.
fromIndex?: number
The index to search from.
Returns: number
The index of the matched value, or -1 if not found.
See Also
Since
2.0.0
Also known as
findFirstIndex (Effect) · indexOf (Lodash, es-toolkit, Ramda) · ❌ (Remeda, Radashi, Modern Dash, Antfu)
Example
const numbers = [1, 2, 3, 2, 4];
// ❌ Deprecated approach
const index = indexOf(numbers, 2);
console.log(index); // 1
// ✅ Recommended approach
const indexNative = numbers.indexOf(2);
console.log(indexNative); // 1
How it works?
Returns the index of the first occurrence of a value.
Deprecated: Use array.indexOf() directly.
Native Equivalent
// ❌ indexOf(arr, value)
// ✅ arr.indexOf(value)
Use Cases
Find element position 📌
Get the index of a specific element.
const colors = ["red", "green", "blue"];
colors.indexOf("green");
// => 1
Check element existence
Determine if an element exists in an array.
const allowed = ["admin", "moderator", "user"];
allowed.indexOf(role) !== -1;
// => true if role is in allowed
Find starting position
Search for an element starting from a specific index.
const items = ["a", "b", "a", "c", "a"];
items.indexOf("a", 2);
// => 2 (first "a" at or after index 2)