1

Let's say I have an array of arrays like so:

var original = [
    [1, 2, 3],
    ['one', 'two'],
    ['blue', 'black', 'red', 'green']
];

I want to transpose this array into a large array that encapsulates every possible combination of each element of my original arrays, using the index of each original array as the position of the value in the master array.

Here's the result I'm looking for:

[
    [1, 'one', 'blue'],
    [2, 'one', 'blue'],
    [3, 'one', 'blue'],
    [1, 'two', 'blue'],
    [2, 'two', 'blue'],
    [3, 'two', 'blue'],
    [1, 'one', 'black'],
    [2, 'one', 'black'],
    [3, 'one', 'black'],

    // and so on until ...

    [1, 'two', 'green'],
    [2, 'two', 'green'],
    [3, 'two', 'green'] // end
];

Here's what I've tried:

// get number of elements that will be in this array
var repeat = _.reduce(original, function (count, options) {
    return count * options.length;
}, 1);

var master = [];

_.each(original, function (options, index) {
    var count = options.length > 0 ? (repeat / options.length) : repeat,
        optionsRepeated = [];

    _(count).times(function () {
        optionsRepeated = optionsRepeated.concat(options)
    });

    master[index] = optionsRepeated;
});

master = _.zip.apply(_, master);
console.log(master);

The problem is that each combination in the final master array isn't unique, and I can't seem to get my head around how to get the result I want. Any ideas? Is there a better way to do this?

Divey
  • 1,699
  • 1
  • 12
  • 22

0 Answers0