0

I'm trying to build/find a function, which will give me all combinations for N number of elements.

The solution below gives me an answer for pairs (i.e. 2 elements).

I'd like to parameterize it, so that I can define the number of combined elements (e.g. 3 elements => ['one', 'two', 'three'], ['one', 'two', 'four'], ... , 4 elements, and so on.

(Bonus internet points if you can tell me the name what I'm looking for (cartesian-product?)!)

var array = ['one', 'two', 'three', 'four', 'five']

// get pairs
var result = array => array.flatMap((v, i) => array.slice(i+1).map( w => [v, w] ));

console.log(result(array))

// output:
// [
//  ["one", "two"],
//  ["one", "three"],
//  ["one", "four"],
//  ["one", "five"],
//  ["two", "three"],
//  ["two", "four"],
//  ["two", "five"],
//  ["three", "four"],
//  ["three", "five"],
//  ["four", "five"]
// ]
Nick Grealy
  • 24,216
  • 9
  • 104
  • 119

1 Answers1

1

I think this is your solution.

/** 
 * Usage Example:
 * 
 * console.log(combination(['A', 'B', 'C', 'D'], 2, true)); // [[ 'A','A' ], [ 'A', 'B' ]...] (16 items)
 * console.log(combination(['A', 'B', 'C', 'D'])); // [['A', 'A', 'A', 'B' ],.....,['A'],] (340 items)
 * console.log(comination(4, 2)); // all posible values [[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 0, 0 ], [ 0, 1 ], [ 0, 2 ]...] (20 items)
 */
function combination(item, n) {
  const filter = typeof n !=='undefined';
  n = n ? n : item.length;
  const result = [];
  const isArray = item.constructor.name === 'Array';

  const pow = (x, n, m = []) => {
    if (n > 0) {
      for (var i = 0; i < 4; i++) {
        const value = pow(x, n - 1, [...m, isArray ? item[i] : i]);
        result.push(value);
      }
    }
    return m;
  }
  pow(isArray ? item.length : item, n);

  return filter ? result.filter(item => item.length == n) : result;
}

console.log("#####first sample: ", combination(['A', 'B', 'C', 'D'], 2)); // with filter
console.log("#####second sample: ", combination(['A', 'B', 'C', 'D'])); // without filter
console.log("#####third sample: ", combination(4, 2)); // just number
  • Thanks @Danilo, nice answer. One problem, It's showing duplicates... for example: `[["A", "A"], ["B", "B"], ["C", "C"]`. Were you able to exclude them? – Nick Grealy Oct 19 '21 at 04:52
  • If you could provide some explanation of how your solution works, that'd be great! (e.g. inline comments?) – Nick Grealy Oct 19 '21 at 11:17