TypeScript Array findIndex() Method
Last Updated :
12 Jul, 2024
Improve
The findIndex() function in TypeScript helps you find the index position of the first element in an array that meets a specified condition. If no element meets the condition, it returns -1.
Syntax
array.findIndex(callbackFn(value, index, array): boolean): number
Parameters
- callbackFn: A function that is called for each element in the array. It takes three arguments:
- element: Here we have to pass the current element that is being processed in the array.
- index: Here we have to pass the index position of the current component which is being processed in the array.
- array: Here we have to pass the array on which findIndex() was called upon.
Return Value:
Returns the index position of the element in an array if it meets the given condition otherwise it will return -1.
Example 1: Finding the Index of the First Even Number
In this example we finds the index of the first even number in the numbers array using findIndex().
const numbers: number[] = [1, 3, 8, 5, 2];
const evenIndex: number = numbers.findIndex(
(number: number) => number % 2 === 0
);
console.log(evenIndex);
Output:
2
Example 2: Finding the Index of the First Odd Number
In this example we finds the index of the first odd number in the numbers
array using findIndex()
.
const numbers: number[] = [2, 4, 8, 5, 2];
const oddIndex: number = numbers.findIndex(
(number: number) => number % 2 === 1
);
console.log(oddIndex);
Output:
3