Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Determine the Frequency of Elements in an Array...

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
  • Using the reduce method
  • Using the Map data structure

Using a for-loop

  • In this method, we utilize a for loop to iterate through each element of the input array. We maintain an empty object called frequency to store the frequencies of each unique element.
  • Inside the loop, we check if the current element 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:

Javascript




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

  • 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:

Javascript




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

  • We start by creating an empty Map called frequency. We then iterate through each element of the input array using a for…of loop.
  • For each element, we use the Map.set() method to either update its existing count in the Map or initialize it with a count of 1.
  • The key in the Map represents the unique element from the array, and the value represents its frequency. After processing all elements, we return the Map object, which contains the frequencies of each unique element.
  • If you want to convert the Map to a regular object (similar to the previous methods), you can use Object.fromEntries(frequencyMap) as shown in the example, which converts the Map key-value pairs into an object with properties representing the unique elements and values representing their frequencies.

Example:

Javascript




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 }
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments