lodash.combinations

Calculates all possible combinations of a certain size.

Usage no npm install needed!

<script type="module">
  import lodashCombinations from 'https://cdn.skypack.dev/lodash.combinations';
</script>

README

lodash.combinations

_.combinations(collection, n)

Calculates all possible combinations of a certain size.

argument description
collection A collection of distinct values to calculate the combinations from.
n The number of values to combine.

Returns a new array.

setup

npm

npm i lodash.combinations

ES module

import 'lodash.combinations';
import _ from 'lodash';

Node

require('lodash.combinations');
let _ = require('lodash');

browser

<script src="https://unpkg.com/lodash"></script>
<script src="https://unpkg.com/lodash.combinations"></script>

usage

let combinations = _.combinations([true, {a: 1}, null], 2);
// => [[true, {a: 1}], [true, null], [{a: 1}, null]]

Calculate all possible combinations of all possible sizes.

let combinations = _.flatMap([2, 4, 6], (v, i, a) => _.combinations(a, i + 1));
// => [[2], [4], [6], [2, 4], [2, 6], [4, 6], [2, 4, 6]]

Also accepts array-like values.

let combinations = _('abcde').combinations(3).map(v => _.join(v, '')).value();
// => ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']

see also