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