Advertisement
informaticage

Dict sum common items

Nov 14th, 2022
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function makeOccurrenceCounter(arr) {
  2.     const occDict = {};
  3.  
  4.     for(let item of arr) {
  5.         if(occDict[item]) {
  6.             occDict[item]++;
  7.         } else {
  8.             occDict[item] = 1;
  9.         }
  10.     }
  11.  
  12.     return occDict;
  13. }
  14.  
  15. function common(arr1, arr2, arr3) {
  16.     const [occ1, occ2, occ3] = [
  17.         makeOccurrenceCounter(arr1),
  18.         makeOccurrenceCounter(arr2),
  19.         makeOccurrenceCounter(arr3),
  20.     ];
  21.  
  22.     const minOcc = {};
  23.  
  24.     const merged = [...arr1, ...arr2, ...arr3];
  25.    
  26.     for(let item of merged) {
  27.         minOcc[item] = Math.min(
  28.             occ1[item] || 0,
  29.             occ2[item] || 0,
  30.             occ3[item] || 0,
  31.         )
  32.     }
  33.  
  34.     return minOcc;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement