Find the Index of all Occurrences of an Element in JS Array

avatar

Borislav Hadzhiev

Last updated: Oct 8, 2021

banner

Photo from Unsplash

Find the Index of all Occurrences of an Element in Array #

To get the index of all occurrences of an element in a JavaScript array:

  1. Create an empty array, that will store the indexes.
  2. Use a for loop and loop from 0 up to the array's length.
  3. For each iteration of the loop, check if the element at that index is equal to the specific element. If it is, push the element's index to the indexes array.
index.js
const arr = ['a', 'b', 'a', 'c', 'a']; const indexes = []; for (let index = 0; index < arr.length; index++) { if (arr[index] === 'a') { indexes.push(index); } } console.log(indexes); // 👉️ [0, 2, 4]

In the code snippet, we create an indexes array that will hold the indexes of an element's occurrences.

We use a simple for loop and iterate for arr.length times. On each iteration we check if the element at that index is equal to the specific element we're checking for.

If it is, we push the index of the element in the indexes array.

Indexes are zero-based in JavaScript, therefore the first element in the array has an index of 0 and the last element an index of arr.length - 1.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.