How to use the forEach Method In Javascript
In this method, we utilize the forEach method to iterate through each element of the input array. We maintain an empty object called frequency to store the frequencies of each unique element.
For each element in the array, we check if it already exists as a property in the frequency object. If it does, we increment the corresponding property’s value by 1, effectively counting its frequency. If the element is not yet a property in the frequency object, we initialize it with a value of 1, indicating that we’ve encountered it once.
After processing all elements in the array, we return the frequency object, which now contains the frequencies of each unique element in the input array.
Example:
function calculateElementFrequenciesWithForEach(inputArray) {
const frequencies = {};
inputArray.forEach(item => {
frequencies[item] = (frequencies[item] || 0) + 1;
});
return frequencies;
}
const inputData = [1, 1, 2, 4, 4, 3, 3, 4, 5, 4, 4, 4, 3, 3];
const resultObject = calculateElementFrequenciesWithForEach(inputData);
console.log(resultObject);
Output
{ '1': 2, '2': 1, '3': 4, '4': 6, '5': 1 }
JavaScript Program to Determine the Frequency of Elements in an Array and Represent it as an Object
In this article, we are going to learn how can we find the frequency of elements in an array and represent it as an object. The frequency of elements in an array in JavaScript refers to how many times each unique element appears in the array.
These are the following approaches by using these we can find the frequency of elements:
Table of Content
- Using a for-loop
- Using the reduce method
- Using the Map
- Using the forEach Method