The indexOf() method returns the index of the first occurrence of a specified value in an array, or -1 if it is not present. The array is searched from the beginning to the end, starting at fromIndex.
The syntax of Array.indexOf() method is:
indexOf(searchElement: T, fromIndex?: number): number
This indexOf() method of Array returns the index of the first occurrence of a value in an array.
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
fromIndex | optional | The index at which to start searching. Defaults to 0. If the index is greater than or equal to the array's length, -1 is returned, meaning the array will not be searched. If the provided index is a negative number, it is taken as the offset from the end of the array. |
Array.indexOf() returns value of type number
.
The indexOf() method can be used to find the index of the first occurrence of a number in an array.
For example,
arr
with numeric values [1, 2, 3, 1, 2, 3].indexOf(2)
to find the first occurrence of the number 2 in the array.index
.index
to the console.const arr = [1, 2, 3, 1, 2, 3];
const index = arr.indexOf(2);
console.log(index);
1
The indexOf() method can be used to find the index of the first occurrence of a string in an array.
For example,
arr
with string values ['apple', 'banana', 'cherry', 'apple'].indexOf('apple')
to find the first occurrence of the string 'apple' in the array.index
.index
to the console.const arr = ['apple', 'banana', 'cherry', 'apple'];
const index = arr.indexOf('apple');
console.log(index);
0
The indexOf() method can be used with a fromIndex parameter to start the search from a specific index.
For example,
arr
with numeric values [1, 2, 3, 1, 2, 3].indexOf(2, 3)
to find the first occurrence of the number 2 in the array, starting the search from index 3.index
.index
to the console.const arr = [1, 2, 3, 1, 2, 3];
const index = arr.indexOf(2, 3);
console.log(index);
4
In this TypeScript tutorial, we learned about indexOf() method of Array: the syntax and few working examples with output and detailed explanation for each example.