0

What is the easiest way to make grouped arrays by count in ES6?

For example I have an array with 4 items that I would like to group into groups of up to 3:

var original = [1, 2, 3, 4]
groupByCount(original, 3)

output:

[1, 2, 3]
[1, 3, 4]
[1, 2, 4]
[2, 3, 4]
[1]
[2]
[3]
[4]
[1, 2]
[2, 3]
[1, 4]
[2, 4]
[3, 4]
[1, 3]

Order insensitive.

Harry
  • 52,711
  • 71
  • 177
  • 261
  • Something like https://stackoverflow.com/questions/9960908/permutations-in-javascript ? (Would `groupByCount` ever be called with the second parameter greater than the length of `original`?) – CertainPerformance Jul 12 '18 at 06:30
  • High level idea is doing a factorial of array.length to know the maximum number of occurrences, then filter out all combinations that has a length that greater than 3 (your condition) – Isaac Jul 12 '18 at 06:30
  • @CertainPerformance Sort of, but those are order sensitive and don't have a limit. – Harry Jul 12 '18 at 06:33
  • Order insensitive is combinations not permuations – Rainb Jul 12 '18 at 06:41

1 Answers1

3

This is actually a combination question. You're asking what is the algorithm to combine an array with 4 items, no repetitions. This algorithm does solve your problem. It is a recurisve way to solve this.

function printCombinations(array, k) {
        var combinations = [];
    
        function run(level, start) {
            for (var i = start; i < array.length - k + level + 1; i++) {
                combinations[level] = array[i];
                if (level < k - 1) {
                    run(level + 1, i + 1);
                } else {
                    console.log(combinations.join(" "));
                }
            }
    
        }
        run(0, 0);
    }
    
    function groupByCount(array, length) {
        for (var i = 0; i < length; i++) {
            printCombinations(array, i + 1);
        }
    }
    groupByCount([1,2,3,4], 3)

As far as I know there is no "native ES6" way to do this.

Rainb
  • 1,965
  • 11
  • 32