Counting the occurrences of JavaScript array elements and put in a new 2d array

We are required to write a JavaScript function that takes in an array of literal values. The function should then count the frequency of each element of the input array and prepare a new array on that basis.

For example ? If the input array is ?

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

Then the output should be ?

const output = [
   [5, 3],
   [2, 5],
   [9, 1],
   [4, 1]
];

Using forEach with Context Object

The code for this will be ?

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

const frequencyArray = (arr = []) => {
   const res = [];
   arr.forEach(function(el) {
      if (!this[el]) {
         this[el] = [el, 0];
         res.push(this[el])
      };
      this[el][1]++
   }, {});
   return res;
};

console.log(frequencyArray(arr));
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]

Using Map for Cleaner Approach

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

const frequencyArrayMap = (arr = []) => {
   const frequency = new Map();
   
   // Count frequencies
   arr.forEach(el => {
      frequency.set(el, (frequency.get(el) || 0) + 1);
   });
   
   // Convert to 2D array
   return Array.from(frequency.entries());
};

console.log(frequencyArrayMap(arr));
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]

Using Object with Object.entries

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

const frequencyArrayObject = (arr = []) => {
   const frequency = {};
   
   arr.forEach(el => {
      frequency[el] = (frequency[el] || 0) + 1;
   });
   
   return Object.entries(frequency).map(([key, value]) => [Number(key), value]);
};

console.log(frequencyArrayObject(arr));
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]

Comparison

Method Readability Performance Memory
forEach with Context Complex Good Efficient
Map Excellent Good Moderate
Object + Object.entries Good Good Efficient

How It Works

The first method uses forEach with a context object as the second parameter. The context object ({}) serves as this inside the callback function, allowing us to store frequency data directly on it.

The Map approach is more modern and readable, using Map.prototype.entries() to convert the frequency map into the required 2D array format.

Conclusion

All three methods effectively count array element frequencies and return 2D arrays. The Map approach offers the best readability, while the Object method provides a good balance of clarity and performance.

Updated on: 2026-03-15T23:19:00+05:30

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements