Horje
TypeScript Array findIndex() Method

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().

TypeScript
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().

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

Output:

3

FAQs – TypeScript Array findIndex() Method

How does findIndex() handle elements that do not satisfy the condition?

If no elements satisfy the condition specified in the callbackFn, findIndex() returns -1.

What happens if the callbackFn always returns false?

If the callbackFn always returns false, findIndex() will return -1, indicating that no elements satisfy the condition.

How does findIndex() handle empty arrays?

For an empty array, findIndex() returns -1 since there are no elements to test.

Can findIndex() be used to find the index of objects in an array?

Yes, findIndex() can be used to find the index of objects in an array by testing object properties in the callbackFn.

What is the difference between findIndex() and indexOf()?

findIndex() uses a testing function to determine the index of the first element that satisfies a condition, while indexOf() searches for a specific value and returns its index.




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Jest vs Mocha: Which one Should You Choose? Jest vs Mocha: Which one Should You Choose?
JavaScript Program to Find the Sum of Digits in a Factorial JavaScript Program to Find the Sum of Digits in a Factorial
JavaScript Program to Find Sum of Even Numbers of an Array JavaScript Program to Find Sum of Even Numbers of an Array
Cookies in JavaScript Cookies in JavaScript
JavaScript Cookies JavaScript Cookies

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11