find the index of an element in an array in typescript

There are multiple ways to find the index of an element in an array in TypeScript. Some common approaches include using the indexOf() method, the findIndex() method, or the includes() method if you only need to check if an element exists in the array.

Here's an example of using the indexOf() method in TypeScript:

index.ts
const myArray: number[] = [10, 20, 30];

const index: number = myArray.indexOf(20);

console.log(index); // Output: 1
118 chars
6 lines

In this example, we have an array of numbers called myArray, and we want to find the index of the element with a value of 20. We use the indexOf() method on the array, passing 20 as the argument, which returns the index of the first occurrence of 20 in the array.

If you want to find the index of an object or custom type in the array, you'll need to use the findIndex() method and provide a callback function that returns true when the desired element is found. For example:

index.ts
interface Person {
  id: number;
  name: string;
}

const people: Person[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const index: number = people.findIndex(person => person.id === 2);

console.log(index); // Output: 1
267 chars
15 lines

In this example, we have an array of Person objects, and we want to find the index of the person with an id of 2. We use the findIndex() method on the array, passing a callback function that checks if the person's id is equal to 2. If a match is found, the callback function returns true and the index of that element is returned.

Finally, if you only need to check if an element exists in the array, you can use the includes() method. This method returns a boolean value indicating whether the array contains the specified element. For example:

index.ts
const myArray: string[] = ['apple', 'banana', 'cherry'];

const hasBanana: boolean = myArray.includes('banana');

console.log(hasBanana); // Output: true
154 chars
6 lines

In this example, we have an array of strings called myArray, and we want to check if it contains the string 'banana'. We use the includes() method on the array, passing 'banana' as the argument, which returns true since 'banana' is present in the array.

gistlibby LogSnag