How to use Array.findIndex() In Typescript

In TypeScript, Array.findIndex() is employed to discover the index of the first array element that satisfies a specified condition defined by a callback function. It returns the index or -1 if not found.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue);

Example: The below code implements the findIndex() method to find the index of array based on its value.

Javascript
interface Person {
    id: number;
    name: string;
}

const array: Person[] = [
    { id: 1, name: "Radha" },
    { id: 2, name: "Megha" },
    { id: 3, name: "Nikita" },
];

const result1: number = array.
    findIndex(item => item.id === 2);
console.log("Index:", result1);

const result2: number = array.
    findIndex(item => item.name === "Nikita");
console.log("Index:", result2);

Output:

Index: 1
Index: 2

How to get the Index of an Array based on a Property Value in TypeScript ?

Getting the index of an array based on a property value involves finding the position of an object within the array where a specific property matches a given value. The below approaches can be used to accomplish the task.

Table of Content

  • Using Array.findIndex()
  • Using reduce() method
  • Using for loop
  • Using a Custom Function

Similar Reads

Using Array.findIndex()

In TypeScript, Array.findIndex() is employed to discover the index of the first array element that satisfies a specified condition defined by a callback function. It returns the index or -1 if not found....

Using reduce() method

In this approach, the reduce() method iterates over a Person array, searching for an object with a specific id and name. It accumulates the index using a callback function, providing flexibility for custom search conditions....

Using for loop

In this approach, for loop iterates through each element in the array. Within the loop, it checks if the id property of the current element matches the target ID. If a match is found, it stores the index and breaks out of the loop....

Using a Custom Function

Using a custom function, the TypeScript code iterates through an array of objects, comparing a specified property value and returning the index if found, or -1 otherwise....