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)