How to use the reduce method In Javascript
- We start with an empty object {} as the initial accumulator. The reduce method processes each element in the array.
- For each element: It checks if the element already exists as a property in the accumulator object using accumulator[element]. If it does, it increments the value by 1. If it doesn’t exist, it initializes it with a value of 1.
- Finally, the reduce method returns the accumulated object, which contains the frequencies of each unique element in the input array.
Example:
function calculateElementOccurrences(inputArray) {
return inputArray
.reduce((occurrences, element) => {
occurrences[element] =
(occurrences[element] || 0) + 1;
return occurrences;
}, {});
}
const newData =
[5, 6, 6, 7, 7, 7, 8, 8, 8, 8];
const occurrencesObject =
calculateElementOccurrences(newData);
console.log(occurrencesObject);
Output
{ '5': 1, '6': 2, '7': 3, '8': 4 }
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