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.

let exampleArrStr: Array<string> = [
  'infinitbility',
  'notebility',
  'repairbility',
];

let strIndex = exampleArrStr.indexOf('repairbility');
console.log('exampleArrStr index', strIndex);

Output

typescript, array, indexOf, example
TypeScript, array indexOf example.

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.

interface Users {
  id: number;
  name: string;
}
let exampleArrObj: Array<Users> = [
  { id: 1, name: 'infinitbility' },
  { id: 2, name: 'notebility' },
  { id: 3, name: 'repairbility' },
];

let objIndex = exampleArrObj.findIndex((e: Users) => e.name == 'notebility');
console.log('exampleArrObj index', objIndex);

Output

typescript, findIndex, example
TypeScript, findIndex example.

Thanks for reading…