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]
];

Example

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(el => {
      if (!this[el]) {
         this[el] = [el, 0];
         res.push(this[el])
      };
      this[el][1] ++
   }, {});
   return res;
};
console.log(frequencyArray(arr));

Output

And the output in the console will be −

[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]

Updated on: 24-Nov-2020

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements