Open In App

TypeScript Array findIndex() Method

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

Javascript




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.

Javascript




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


Output:

3

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads