1

I'm trying to generate all possible combinations of an array with undefined as a replacement value.

The values of the array are fixed in place.

So for example we have this array (the array can have a length of x):

const items = [1, 2];

The function that I'm trying to build should generate:

[
 [1, 2],
 [1, undefined],
 [undefined, 2],
 [undefined, undefined]
]
Peter O.
  • 32,158
  • 14
  • 82
  • 96
toonvanstrijp
  • 417
  • 1
  • 5
  • 18
  • 1
    Does this answer your question? [Javascript - Generating all combinations of elements in a single array (in pairs)](https://stackoverflow.com/questions/43241174/javascript-generating-all-combinations-of-elements-in-a-single-array-in-pairs) – makeitmorehuman Nov 10 '19 at 11:21
  • @AliHabibzadeh unfortunately not, the values in my array are fixed in place. What I'm trying to do is generate the result in my comment. And the answer you're referring to doesn't :) – toonvanstrijp Nov 10 '19 at 11:23

1 Answers1

1

Here you go. I hope the additional comments substitute a long and boring prologue.

/* your array to work with. the length does not matter as the algorithm adapts to it */
const items = [1, 2, 3, 4];

/* the array containing the results */
const resultSet = [];

/* the number of rounds you need to create all possible combinations */
const maxRounds = Math.pow(2, items.length);

/* first we add the original list to the result set */
resultSet.push(items);

/* now we do the number of rounds, starting with index 1, until all combinations are set */
for (let round = 1; round < maxRounds; round++)
{
    /* create a clone, in order to not manipulate the original array by reference */
    const result = JSON.parse(JSON.stringify(items));

    /* generate the binary representation of the current round */
    /* this gives us a combination of only zeros ans ones */
    let binary = Number(round).toString(2);

    /* if the length doesn't match, add one additional zero to the left side */
    if (binary.length < items.length)
    {
        binary = '0' + binary;
    }

    /* now walk the line of 0s and 1s and decide whether to set 'undefined' or not */
    for (let pointer = 0; pointer < items.length; pointer++)
    {
        if (binary[pointer] === '1')
        {
            result[pointer] = undefined;
        }
    }

    /* add the new array to the result set */
    resultSet.push(result);
}

/* see the final list */
console.log(resultSet);