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.
1interface User {2 id: number;3 name: string;4}56interface Api {7 status: number;8 users: Array<User>;9}1011let users: Array<User> = [12 { id: 1, name: 'infinitbility' },13 { id: 2, name: 'notebility' },14 { id: 3, name: 'repairbility' },15];
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.
1users.findIndex(e => e.id == 2);
In below example, i have added example of if findIndex method got true
condition or false
both.
1interface User {2 id: number;3 name: string;4}56interface Api {7 status: number;8 users: Array<User>;9}1011let users: Array<User> = [12 { id: 1, name: 'infinitbility' },13 { id: 2, name: 'notebility' },14 { id: 3, name: 'repairbility' },15];1617// found index example18users.findIndex(e => e.id == 2);1920// not found index example21users.findIndex(e => e.id == 3);
Output

Thanks for reading…
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.