Unique number of occurrences of elements in an array in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function should whether all the integers that are present in the array appear for unique number of times or not.

If they do, the function should return true, false otherwise.

For example −

If the input array is −

const arr = [7, 5, 5, 8, 2, 4, 7];

Then the output should be −

const output = false;

because both the integers 7 and 5 appears for 2 times each.

We will first use a hash map to map integers to their frequencies(occurrences) and then use that map to build a set that stores unique frequencies.

Example

Following is the code −

const arr = [7, 5, 5, 8, 2, 4, 7];
const uniqueAppearances = (arr = []) => {
   const map = {};
   const set = new Set();
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      map[el] = (map[el] || 0) + 1;
   };
   for(key in map){
      const value = map[key];
      if(set.has(value)){
         return false;
      };
      set.add(value);
   };
   return true;
};
console.log(uniqueAppearances(arr));

Output

Following is the console output −

false

Updated on: 22-Jan-2021

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements