2

I'm trying to combine all elements of a multidimensional Array to have a combination of elements.

e.g. If I have

var array = [
      ['a'],
      ['1', '2', '3', '4'],
      ['A']
];

The result must look like:

["a1A", "a2A", "a3A", "a4A"]

I could realise this result with the following code:

  var finalArray = [];
  var f1 = 0;

  for (var i = 0; i < array.length - 1; i ++) {
        f1 = 0;
        for (var j = 0; j < array[i].length; j ++) {
              for (var k = 0; k < array[i + 1].length; k ++) {
                    if (finalArray[f1])
                          finalArray[f1] += array[i + 1][k];
                    else 
                          finalArray[f1] = array[i][j] + array[i + 1][k];

                    f1 ++;
              }
        }
  }

  console.log(finalArray);

The Problem is if I add more elements to the first or last member, it does not work as expected.

for example this array

var array = [
      ['a', 'b'],
      ['1', '2', '3', '4'],
      ['A']
];

returns:

["a1A", "a2A", "a3A", "a4A", "b1", "b2", "b3", "b4"]

which should be:

["a1A", "a2A", "a3A", "a4A", "b1A", "b2A", "b3A", "b4A"]

Any help to fix my code is highly appreciated.

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86
hoomb
  • 649
  • 2
  • 12
  • 24

1 Answers1

3

You could use an iterative and recursive approach for variable length of parts an their length.

function combine(array) {
    function c(part, index) {
        array[index].forEach(function (a) {
            var p = part.concat(a);
            if (p.length === array.length) {
                r.push(p.join(''));
                return;
            }
            c(p, index + 1);
        });
    }

    var r = [];

    c([], 0);
    return r;
}

var result = combine([['a', 'b', 'c'], ['1', '2', '3', '4'], ['A', 'B']]);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392