Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda