

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- Unique Number of Occurrences in Python
- JavaScript Count the number of unique elements in an array of objects by an object property?
- How to count number of occurrences of repeated names in an array - JavaScript?
- Counting unique elements in an array in JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- How to count the number of occurrences of all unique values in an R data frame?
- Count occurrences of the average of array elements with a given number in C++
- Return an array with the number of nonoverlapping occurrences of substring in Python
- Rearranging elements of an array in JavaScript
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Iterating through an array, adding occurrences of a true in JavaScript
- Sum of distinct elements of an array in JavaScript
- Find the Number of Unique Pairs in an Array using C++
- Sum of distinct elements of an array - JavaScript
- Finding sum of all unique elements in JavaScript
Advertisements