Hello Friends 👋,
Welcome To Infinitbility! ❤️
To get index value of element typescript have indexOf()
and findIndex()
method but both have different poupose of use.
Today, we will learn how to get index array elements in typescript and we will see examples with an array of string and an array of objects.
Let’s first understand when use indexOf()
or findIndex()
method.
The indexOf() method is used for an array of primitive datatypes like string, number, etc or you can also say single dimension array.
The findIndex() method use when find index value from object element.
TypeScript indexOf() example
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
1let exampleArrStr: Array<string> = [2 'infinitbility',3 'notebility',4 'repairbility',5];67let strIndex = exampleArrStr.indexOf('repairbility');8console.log('exampleArrStr index', strIndex);
Output

TypeScript findIndex() example
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
1interface Users {2 id: number;3 name: string;4}5let exampleArrObj: Array<Users> = [6 { id: 1, name: 'infinitbility' },7 { id: 2, name: 'notebility' },8 { id: 3, name: 'repairbility' },9];1011let objIndex = exampleArrObj.findIndex((e: Users) => e.name == 'notebility');12console.log('exampleArrObj index', objIndex);
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.