0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Frequency of Elements in Array

Use a JavaScript object to count frequencies by looping through the array and updating counts with freq[element] = (freq[element] || 0) + 1.
📋

Examples

Input[1, 2, 2, 3, 3, 3]
Output{"1":1,"2":2,"3":3}
Input["apple", "banana", "apple", "orange", "banana", "banana"]
Output{"apple":2,"banana":3,"orange":1}
Input[]
Output{}
🧠

How to Think About It

To find how many times each element appears, go through each item in the array one by one. Keep a record (like a list or object) where you add 1 to the count for that item every time you see it. At the end, you have a list showing each element and how many times it showed up.
📐

Algorithm

1
Create an empty object to store frequencies.
2
For each element in the array, check if it is already in the object.
3
If it is, add 1 to its count; if not, set its count to 1.
4
After processing all elements, return the object with frequencies.
💻

Code

javascript
function findFrequency(arr) {
  const freq = {};
  for (const item of arr) {
    freq[item] = (freq[item] || 0) + 1;
  }
  return freq;
}

const array = [1, 2, 2, 3, 3, 3];
console.log(findFrequency(array));
Output
{"1":1,"2":2,"3":3}
🔍

Dry Run

Let's trace [1, 2, 2, 3, 3, 3] through the code

1

Start with empty frequency object

freq = {}

2

Process first element 1

freq = {"1": 1}

3

Process second element 2

freq = {"1": 1, "2": 1}

4

Process third element 2 again

freq = {"1": 1, "2": 2}

5

Process fourth element 3

freq = {"1": 1, "2": 2, "3": 1}

6

Process fifth element 3 again

freq = {"1": 1, "2": 2, "3": 2}

7

Process sixth element 3 again

freq = {"1": 1, "2": 2, "3": 3}

ElementFrequency Object
1{"1":1}
2{"1":1,"2":1}
2{"1":1,"2":2}
3{"1":1,"2":2,"3":1}
3{"1":1,"2":2,"3":2}
3{"1":1,"2":2,"3":3}
💡

Why This Works

Step 1: Initialize frequency object

We start with an empty object freq to store counts of each element.

Step 2: Count each element

For each element, we check if it exists in freq. If yes, add 1; if no, start at 1.

Step 3: Return frequency object

After processing all elements, freq holds the count of each element, which we return.

🔄

Alternative Approaches

Using Map object
javascript
function findFrequencyMap(arr) {
  const freqMap = new Map();
  for (const item of arr) {
    freqMap.set(item, (freqMap.get(item) || 0) + 1);
  }
  return Object.fromEntries(freqMap);
}

console.log(findFrequencyMap([1,2,2,3,3,3]));
Map can handle keys of any type and preserves insertion order but requires conversion to object for JSON output.
Using reduce method
javascript
const findFrequencyReduce = arr => arr.reduce((acc, item) => {
  acc[item] = (acc[item] || 0) + 1;
  return acc;
}, {});

console.log(findFrequencyReduce([1,2,2,3,3,3]));
Using reduce is concise and functional style but may be less clear for beginners.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the array once, so time grows linearly with input size.

Space Complexity

Extra space is used to store counts for each unique element, which can be up to the array size.

Which Approach is Fastest?

Using a plain object or Map both offer O(n) time; reduce is concise but similar in performance.

ApproachTimeSpaceBest For
Object with loopO(n)O(n)Simple and fast for string/number keys
Map objectO(n)O(n)Keys of any type, preserves order
Array reduceO(n)O(n)Concise functional style
💡
Use freq[element] = (freq[element] || 0) + 1 to count frequencies easily.
⚠️
Beginners often forget to initialize counts and try to increment undefined values directly.