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

avatar

Borislav Hadzhiev

Fri Oct 08 20211 min read

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. In 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee