How to usethe Javascript forEach() 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.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Example: In this example, we will iterate over the elements of an array using the forEach() method, count the number of occurrences of all the elements of the array, and print them in the console.
let arr = [
'geeks', 2, 'geeks', 2, 'Javascript', 4,
'Javascript', 5, 'for', 6, 'Javascript', 1,
'for', 5, 7, 8, 'for'
];
const counter = {};
arr.forEach(ele => {
if (counter[ele]) {
counter[ele] += 1;
} else {
counter[ele] = 1;
}
});
console.log(counter)
Output
{ '1': 1, '2': 2, '4': 1, '5': 2, '6': 1, '7': 1, '8': 1, geeks: 2, Javascript: 3, for: 3 }
Count occurrences of all items in an array in JavaScript
We will see how to count occurrences of all items in an array in JavaScript. One of the most common methods of doing this is by using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method.
Example:
Input: [1,3,4,3,4,1,3,3,3,4] Output: {"1": 2, "3" : 5, "4" 3}
Counting the occurrences of all the items in an array can be done in the following ways:
Table of Content
- Approach 1: Using the Javascript forEach() method
- Approach 2: Using reduce() method
- Approach 3: Using filter() method
- Approach 4: Using for…of loop
- Approach 5: Using Lodash _.frequencies() Method
- Approach 6: Using ES6 Map