Open In App

TypeScript Array findIndex() Method

The findIndex() function, in TypeScript of array instances, helps you to find the index position of the element in an array that meets a condition, if no element meets the given condition it returns -1.

Syntax:

array.findIndex(callbackFn(value, index, array): boolean): number

Parameters:

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: To demonstrate finding the index position of first occurrence of even number using findIndex() method.




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: To demonstrate finding the first position of first occurrence of odd number using findIndex() method.




const numbers: number[] = [2, 4, 8, 5, 2];
const oddIndex: number = numbers.findIndex(
    (number: number) => number % 2 === 1
);
console.log(oddIndex);

Output:

3
Article Tags :