Harry
Harry

Reputation: 54959

javascript group by determined count

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.

Upvotes: 0

Views: 234

Answers (1)

Rainb
Rainb

Reputation: 2465

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.

Upvotes: 3

Related Questions