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 and generates a frequency map of all possible combinations within each array. The function counts how many times each element and combination appears across all arrays.

For example, if we have the following arrays:

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

The function should generate all possible combinations from each array and count their frequencies across all input arrays.

How It Works

The solution involves three main steps:

  • Generate combinations: Find all possible subsets of elements within each array
  • Sort and format: Sort elements within combinations for consistent representation
  • Count frequencies: Track how many times each combination appears

Complete Solution

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 

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

Step-by-Step Breakdown

Let's examine each function:

// Generate all combinations of an array
const findMatch = arr => {
    let result = [];
    const pick = (i, t) => {
        if (i === arr.length) {
            t.length && result.push(t);
            return;
        };
        // Include current element or skip it
        pick(i + 1, t.concat(arr[i]));
        pick(i + 1, t);
    };
    pick(0, []);
    return result;
};

// Test with a simple array
console.log(findMatch([1, 2]));
[ [ 1 ], [ 1, 2 ], [ 2 ] ]

Key Features

  • Recursive combination generation: Uses backtracking to find all subsets
  • Sorted output: Elements within combinations are sorted for consistency
  • Frequency counting: Tracks occurrences across multiple arrays
  • Variable arguments: Accepts any number of input arrays using rest parameters

Conclusion

This solution efficiently generates all possible combinations from multiple arrays and creates a frequency map. It's useful for analyzing patterns and relationships between elements across different datasets.

Updated on: 2026-03-15T23:19:00+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements