find index in array in javascript

To find the index of a specific element in an array in JavaScript, you can use the findIndex() method. The findIndex() method returns the index of the first element in the array that satisfies the given condition.

Here's an example code block that demonstrates how to use findIndex() to find the index of an element in an array:

index.tsx
const myArray = [10, 20, 30, 40, 50];

const index = myArray.findIndex(element => element === 30);

console.log(index); // Output: 2
133 chars
6 lines

In the above example, we have an array myArray containing some numbers. We then use the findIndex() method to find the index of the number 30. The findIndex() method takes a callback function as an argument that should return a boolean value based on a given condition. In this case, we are checking if an element in the array is equal to 30. If we find an element that satisfies this condition, findIndex() returns the index of that element (in this case, 2).

related categories

gistlibby LogSnag