Find Equivalent Value and Frequency in Array in JavaScript


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

The function should check whether there exists an integer in the array such that its frequency is same as its value.

If there exists at least one such integer, we should return that integer otherwise we should return -1.

For example −

If the input array is −

const arr = [3, 4, 3, 8, 4, 9, 7, 4, 2, 4];

Then the output should be −

const output = 4;

Example

Following is the code −

const arr = [3, 4, 3, 8, 4, 9, 7, 4, 2, 4];
const checkValueFrequency = (arr = []) => {
   const map = {};
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      map[el] = (map[el] || 0) + 1;
   };
   for(key in map){
      if(+key === map[key]){
         return +key;
      };
   };
   return -1;
};
console.log(checkValueFrequency(arr));

Output

Following is the console output −

4

Updated on: 22-Jan-2021

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements