
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements