Javascript中的Itertools.combinations

And*_*cko 7 javascript

是否有与JavaScript中Python的itertools类似的库?我对排列和组合特别感兴趣。

我没有使用Node.js。

我想做这样的事情:

array = ['a', 'b', 'c', 'd'];

//return non-duplicate combinations of length 2
['a', 'b']
['a', 'c']
['a', 'd']
['b', 'c']
['b', 'd']
['c', 'd']
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

Nin*_*olz 7

您可以使用递归方法来获取具有指定大小的给定数组的排列。

function getPermutations(array, size) {

    function p(t, i) {
        if (t.length === size) {
            result.push(t);
            return;
        }
        if (i + 1 > array.length) {
            return;
        }
        p(t.concat(array[i]), i + 1);
        p(t, i + 1);
    }

    var result = [];
    p([], 0);
    return result;
}

var array = ['a', 'b', 'c', 'd'];

console.log(getPermutations(array, 2));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)