Find Index Of All Occurrences Of An Element In An Array In JS

To find the index of all occurrences of an element in an array in JavaScript, you can use any of these methods –

  1. Use the forEach() loop to iterate the array and in each iteration, check if the current element is equal to the given element.
  2. Use a for loop to iterate the array and in each iteration, and in each iteration, check if the current element is equal to the given element.

Let’s discuss each of these methods in detail below.

find the index of all occurrences of an element in an array in JS

forEach() To Find The Index Of All Occurrences Of An Element In An Array

The forEach() method takes an iterator function as an argument which is called for each element in the array.

See the code below –

let arr = ['a', 'b', 'c', 'd', 'a', 'b', 'c'];

let occurrences = [];

arr.forEach((element, index) => {

  if(element === 'a') occurrences.push(index);

});

console.log(occurrences); [0,4]

In the above code, we have created an array arr with some elements. We have also declared a blank array occurrences where we will store the indexes of all occurrences of element ‘a’.

Then we use forEach() loop to iterate over each element in the array and check if it matches ‘a’ or not. If it does, then we push it’s index to the occurrences array.

At the end, we log occurrences to the console.

Use A for Loop To Find All Occurrences Of An Element In An Array

We can also use a classic for loop to iterate over each element in an array and find all occurrences of an element.

See the code below –

let arr = ['a', 'b', 'c', 'd', 'a', 'b', 'c'];

let occurrences = [];

for(let i=0;i<arr.length;i++){

   if(arr[i] === 'a') occurrences.push(i);

}

console.log(occurrences); //[0,4]

In the above code, we have created an array arr with some elements. We have also declared a blank array occurrences where we will store the indexes of all occurrences of element ‘a’.

Then we use a for loop to iterate over each element in the array and check if it matches ‘a’ or not. If it does, then we push it’s index to the occurrences array.

At the end, we log occurrences to the console.

Conclusion

In this article, we discussed various methods to find the index of all occurrences of an element in a JavaScript array.

You can use any of the above methods depending on your requirement.

If you have any questions or comments, please feel free to post them in the comments section below.

Leave a Reply