Skip to content

Permutation on arrays without duplicate and fixed length

I’m having trouble figuring out how to generate a combination of values.

Given:

const items = ['a', 'b', 'c', 'd', 'e'];

should generate:

[
    ['a', 'b', 'c'],
    ['a', 'b', 'd'],
    ['a', 'b', 'e'],
    ['a', 'c', 'd'],
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],

    ['b', 'c', 'd'],
    ['b', 'c', 'e'],

    ['c', 'd', 'e']
]

It generates a unique combination for all the items in the array. Basically, the length of the array for each item is Math.round(items.length / 2).

Any help would be greatly appreciated.

Answer

You could take a straight forward approach and iterate the array and get the parts of the rest array by respecting the wanted length.

function perm(array, length) {
    return array.flatMap((v, i) => length > 1
        ? perm(array.slice(i + 1), length - 1).map(w => [v, ...w])
        : [[v]]
    );
}

perm(['a', 'b', 'c', 'd', 'e'], 3).forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }