How To Find The Index Of All Occurrences Of An Element In JavaScript Array

How To Find The Index Of All Occurrences Of An Element In JavaScript Array

In this article, you’ll learn how to find the index of all occurrences of an element in Javascript array using the for loop or the .forEach() function. Let’s read this article now.

Find the index of all occurrences of an element in Javascript array

Note: In this article, all the results will be in array form containing all the occurrence indexices.

Using a ‘for’ loop or the Array.prototype.forEach() function

This is the simplest way. Simply iterate over the array and check if the value exists in the array. If it is the same, add its index to the index array.

You can either use the for loop or the Array class’s .forEach() function, both of which usually work the same and return the same output.

Code:

const words = ['spray', 'LearnShareIT', 'spray', 'destruction', 'present', 'spray'];
                
// Create the function to find the index of all occurrences of an element 
function findAllIndexices(arr, val) {
    const indexices = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
          	indexices.push(i);
        }
    }
    return indexices;
}

console.log(findAllIndexices(words, "spray"));
console.log(findAllIndexices(words, "LearnShareIT"));

Note: While you can iterate over an array using the of keyword, a basic for loop would work better in this specific context as it also gives you the current index in the i variable.

Code:

const words = ['spray', 'LearnShareIT', 'spray', 'destruction', 'present', 'spray'];

// Create the function to find the index of all occurrences of an element 
function findAllIndexices(arr, val) {
    const indexices = [];
    arr.forEach((v, i) => {
      	if (v === val) {
          	indexices.push(i);
        }
    });
    return indexices;
}

console.log(findAllIndexices(words,"spray"));
console.log(findAllIndexices(words,"LearnShareIT"));

Note: ()=>{} is the same as function(){} (Anonymous function).

Output

[ 0, 2, 5 ]
[ 1 ]

Using the Array.prototype.map() and Array.prototype.filter() functions

As a reminder, the .map() function creates a shallow copy of the array using the results from calling a callback-function for every value of the iterated array.

The .filter() function creates a shallow copy of the array; however, the shallow copy will only contain the values in which a callback-function (i.e. the filter) will return true.

Additionally, for anyone who forgot or don’t know:

  • A “callback-function” is a function that is passed as a different function’s parameter.
  • A “shallow-copy” is anything that has been copied over but still “point” to the same under-lying properties. Following that, if a change is made to the source or the copy, the properties will change for both copy and source.

Code:

const words = ['spray', 'LearnShareIT', 'spray', 'destruction', 'present', 'spray'];

// Create the function to find the index of all occurrences of an element 
function findAllIndexices(arr, val) {
    const indexices = arr.map((v, i) => v === val ? i : -1).filter(v => v !== -1);
    return indexices;
}

console.log(findAllIndexices(words, "spray"));
console.log(findAllIndexices(words, "LearnShareIT"));

Output

[ 0, 2, 5 ]
[ 1 ]

Summary

This article helps you learn about how to find the index of all occurrences of an element in Javascript array. Let’s try these methods to get your desired results.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *