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