Navigate back to the homepage

how to find the index of an object in an array in typescript?

Infinitbility
TypeScript
February 27th, 2022 · 1 min read
keep affilitate

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}
5
6interface Api {
7 status: number;
8 users: Array<User>;
9}
10
11let 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}
5
6interface Api {
7 status: number;
8 users: Array<User>;
9}
10
11let users: Array<User> = [
12 { id: 1, name: 'infinitbility' },
13 { id: 2, name: 'notebility' },
14 { id: 3, name: 'repairbility' },
15];
16
17// found index example
18users.findIndex(e => e.id == 2);
19
20// not found index example
21users.findIndex(e => e.id == 3);

Output

TypeScript findIndex() Example
TypeScript, findindex () Example

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.

melio affilitate

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to get current date in react native?

React Native, get current date example.

February 14th, 2022 · 1 min read

How to get current month in react native?

React Native, get current month example.

February 14th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]