Hello Friends đź‘‹,

Welcome to Infinitbility.

Today, we are going to learn how we can get index of object based array on object property condition if condition true we should get index of match object.

TypeScript provide findIndex() method to get index of element in array, we can also use this method to find index of object in array.

findIndex() method return -1 if condition not matched.

Supppose we have array of objects like below.

interface User {
  id: number;
  name: string;
}

interface Api {
  status: number;
  users: Array<User>;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility' },
  { id: 2, name: 'notebility' },
  { id: 3, name: 'repairbility' },
];

Now, we are going use findIndex() method with condition to get index of object.

For find index array of objects, we should follow below syntax.

users.findIndex(e => e.id == 2);

In below example, i have added example of if findIndex method got true condition or false both.

interface User {
  id: number;
  name: string;
}

interface Api {
  status: number;
  users: Array<User>;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility' },
  { id: 2, name: 'notebility' },
  { id: 3, name: 'repairbility' },
];

// found index example
users.findIndex(e => e.id == 2);

// not found index example
users.findIndex(e => e.id == 3);

Output

TypeScript findIndex() Example
TypeScript, findindex () Example

Thanks for reading…