find the index of an element in an array in javascript

There are two methods to find the index of an element in an array in JavaScript:

  1. The indexOf() method: It finds the first occurrence of the specified element in the array and returns its index. If the element is not found, it returns -1.
index.tsx
let array = ["apple", "banana", "orange"];
let index = array.indexOf("banana");
console.log(index); // Output: 1
113 chars
4 lines
  1. The findIndex() method: It finds the index of the first element in the array that satisfies the provided testing function. If no element satisfies it, it returns -1.
index.tsx
let array = [10, 20, 30];
let index = array.findIndex(element => element > 15);
console.log(index); // Output: 1
113 chars
4 lines

In both these methods, if you want to find the index of the last occurrence of a specified element in the array, you can reverse the array using the reverse() method before using these methods.

gistlibby LogSnag