How to Find the Index of the Second Occurrence of an Element in JavaScript?

Estimated read time 1 min read

To find the index of the second occurrence of an element in a JavaScript array, you can use the indexOf method in combination with a loop. The indexOf method returns the index of the first occurrence of the specified element in an array, or -1 if the element is not present.

Here’s an example:

const array = [1, 2, 3, 4, 3, 5, 6];

let firstIndex = array.indexOf(3);
let secondIndex = -1;

for (let i = firstIndex + 1; i < array.length; i++) {
  if (array[i] === 3) {
    secondIndex = i;

console.log(secondIndex); // Output: 4

In this example, firstIndex is set to the index of the first occurrence of the element with the value 3 using the indexOf method. Then, a for loop is used to search for the second occurrence of the element starting from firstIndex + 1. If the element is found, its index is stored in secondIndex and the loop is exited using the break statement. If the element is not found, secondIndex remains at its initial value of -1.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply