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)