fueanta

If Array Elements have Unique Frequencies

Jul 2nd, 2021 (edited)
1,348
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const hasUniqueFrequencies = <T>(array: T[]): boolean => {
  2.     const itemCountMap = new Map<T, number>();
  3.  
  4.     for (const item of array) {
  5.         const itemCount = itemCountMap.get(item);
  6.  
  7.         if (itemCount)
  8.             itemCountMap.set(item, itemCount + 1);
  9.         else
  10.             itemCountMap.set(item, 1);
  11.     }
  12.  
  13.     const countSet = new Set<number>(itemCountMap.values());
  14.  
  15.     return itemCountMap.size === countSet.size;
  16. }
  17.  
  18. const array = [2, 2, 3, 3, 3];
  19.  
  20. console.log(hasUniqueFrequencies(array));
  21.  
RAW Paste Data