Generate Ranking with combination of strings in JavaScript


We are required to write a JavaScript function that takes in any number of arrays of numbers. Then the function should return an object that returns a frequency map indicating how many times each element has appeared checking in all the array.

For example, If the arrays are −

const a = [23, 45, 21], b = [45, 23], c = [21, 32], d = [23], e= [32], f=[50, 54];

Then the output should be −

const output = {
   "21": 2,
   "23": 3,
   "32": 2,
   "45": 2,
   "52": 1,
   "54": 1,
   "23, 45": 2,
   "23, 45, 21": 1,
   "21, 32": 1,
   "50 : 54": 1,
   "50" : 1
}

Example

The code for this will be −

const a = [23, 45, 21], b = [45, 23], c = [21, 32], d = [23], e= [32], f=[50, 54];
const findMatch = arr => {
   let result = [];
   const pick = (i, t) => {
      if (i === arr.length) {
         t.length && result.push(t);
         return;
      };
      pick(i + 1, t.concat(arr[i]));
      pick(i + 1, t);
   };
   pick(0, []);
   return result;
};
const sorter = (a, b) => a - b;
const mergeCombination = (arr, obj) => {
   findMatch(arr.sort(sorter)).forEach(el => {
      return obj[el.join(', ')] = (obj[el.join(', ')] || 0) + 1
   });
};
const buildFinalCombinations = (...arrs) => {
   const obj = {};
   for(let i = 0; i < arrs.length; i++){
      mergeCombination(arrs[i], obj);
   };
   return obj;
};
console.log(buildFinalCombinations(a, b, c, d, e, f));

Output

The output in the console −

{
   '21': 2,
   '23': 3,
   '32': 2,
   '45': 2,
   '50': 1,
   '54': 1,
   '21, 23, 45': 1,
   '21, 23': 1,
   '21, 45': 1,
   '23, 45': 2,
   '21, 32': 1,
   '50, 54': 1
}

Updated on: 10-Oct-2020

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements