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

191
Views
Generating all combinations of an array with some exceptions

I had an array like this below

const myArray = [1, 2, 3, 4, 5, 6];

and I was able to get every possible combination's out of it with this function.

function getCombinations(list) {
  var set = [],
    listSize = list.length,
    combinationsCount = 1 << listSize,
    combination;

  for (var i = 1; i < combinationsCount; i++) {
    var combination = [];
    for (var j = 0; j < listSize; j++) {
      if (i & (1 << j)) {
        combination.push(list[j]);
      }
    }
    set.push(combination);
  }
  return set;
}

it works fine and I get 63 possible combination with the array above

my problem begins here i want every possible combination but with one exception, my array of items are in group like this below

const myArray = [
  { groupId: "foo", value: 1 },
  { groupId: "foo", value: 2 },
  { groupId: "foo", value: 3 },
  { groupId: "bar", value: 4 },
  { groupId: "bar", value: 5 },
  { groupId: "zoo", value: 6 },
];

I want to get every possible combination but each combination must only have one item of a group

for example there are correct out put I'm looking for

const myArray = [
  { groupId: "foo", value: 1 },
];

const myArray = [
  { groupId: "foo", value: 1 },
  { groupId: "zoo", value: 6 },
];

const myArray = [
  { groupId: "foo", value: 1 },
  { groupId: "bar", value: 5 },
  { groupId: "zoo", value: 6 },
];

const myArray = [
  { groupId: "bar", value: 5 },
  { groupId: "zoo", value: 6 },
];

As you can see I want to each group only have one of it items in the generated combinations

These are the combination that I don't want to be generated

const myArray = [
  { groupId: "bar", value: 4 },
  { groupId: "bar", value: 5 },
  { groupId: "zoo", value: 6 },
];

const myArray = [
  { groupId: "foo", value: 1 },
  { groupId: "zoo", value: 6 },
  { groupId: "zoo", value: 7 },
];

we have two item with zoo group tag I don't want this outputs.

about 4 years ago · Juan Pablo Isaza
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!