Open In App

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:



Using a for-loop

Example:




function calculateElementFrequencies(inputArray) {
    const frequencies = {};
    for (const item of inputArray) {
        if (frequencies[item]) {
            frequencies[item]++;
        } else {
            frequencies[item] = 1;
        }
    }
    return frequencies;
}
  
const inputData = 
    [1, 1, 2, 4, 4, 3, 3, 4, 5, 4, 4, 4, 3, 3];
const resultObject = 
    calculateElementFrequencies(inputData);
console.log(resultObject);

Output

{ '1': 2, '2': 1, '3': 4, '4': 6, '5': 1 }

Using the reduce method

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 }

Using the Map

Example:




function calculateElementCounts(inputArray) {
    const counts = new Map();
    for (const item of inputArray) {
        counts.set(item, (counts.get(item) || 0) + 1);
    }
    return counts;
}
const inputData = 
    [5, 6, 6, 7, 7, 7, 8, 8, 8, 8];
const countsMap = 
    calculateElementCounts(inputData);
  
const countsObject = 
    Object.fromEntries(countsMap);
console.log(countsObject);

Output
{ '5': 1, '6': 2, '7': 3, '8': 4 }

Article Tags :