Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Generating all combinations of elements in a single array (for cominations of N elements)

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"]
// ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!