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