How to useforEach() Method in Javascript

The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.

Example: In this example The function GFG_Fun iterates through arr, pushing the indices of all occurrences of ‘GFG’ into indexArr.

Javascript
let arr = [
    'GFG', 'Geeks', 'Portal',
    'Computer Science', 'GFG',
    'GFG', 'Geek'
];

let elm = 'GFG';
const indexArr =[];

function GFG_Fun() {
    arr.forEach((element, index) => {
        if (element === elm) {
            indexArr.push(index);
        }
    });
    console.log(indexArr);
}

GFG_Fun();

Output
[ 0, 4, 5 ]

How to find the index of all occurrence of elements in an array using JavaScript ?

The index of all occurrences of elements refers to the positions of each instance of a specific element within an array. We find these indices to locate all occurrences of an element for various operations like counting, filtering, or manipulation within the array.

To find the index of all occurrences of elements in an array using JavaScript, iterate through the array, and for each element, check if it matches the target. If so, record its index. Repeat until all occurrences are found.

We are going to do that with the help of JavaScript`s following methods:

Table of Content

  • Using While Loop
  • Using reduce() Method
  • Using forEach() Method
  • Using map() and filter() Method
  • Using reduce() Method

Similar Reads

Approach 1: Using While Loop

Declare an empty array that stores the indexes of all occurrences of the array element. Visit the array elements one by one using a while loop and if the array elements match with the given element then push the index of the element into an array. After visiting each element of the array, return the array of indexes....

Approach 2: Using reduce() Method

Visit the array elements one by one using reduce() method and if the array elements match with the given element then push the index into the array. After visiting each element of the array, return the array of indexes....

Approach 3: Using forEach() Method

The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array....

Approach 4: Using map() and filter() Method

In this approach, we can use map() and filter() methods to find the index of all occurrences of elements in an array using JavaScript....

Approach 5: Using reduce() Method

The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator....