3

I have a simple Javascript object:

options[0] = {
    title: 'Title 1',
    items: ['a', 'b', 'c']
};

options[1] = {
    title: 'Title 2',
    items: ['1', '2', '3']
};

options[2] = {
    title: 'Title 3',
    items: ['x', 'y', 'z']
};

I need it recursively run the array on itself. The output for the example above should be 27 entries/rows:

a / 1 / x
a / 1 / y
a / 1 / z
a / 2 / x
a / 2 / y
a / 2 / z
a / 3 / x
a / 3 / y
a / 3 / z
b / 1 / x
b / 1 / y
b / 1 / z
b / 2 / x
b / 2 / y
b / 2 / z
b / 3 / x
b / 3 / y
b / 3 / z
c / 1 / x
c / 1 / y
c / 1 / z
c / 2 / x
c / 2 / y
c / 2 / z
c / 3 / x
c / 3 / y
c / 3 / z

Here's what I've tried so far:

fn_options(options);

function fn_options(options) {
  $.each(options, function( index, option ) {
        $.each(option.items, function( i, item ) {
      console.log(item);
    });
  });
}

Basic fiddle here: http://jsfiddle.net/6D89F/1/

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
AFRC
  • 902
  • 3
  • 9
  • 27
  • 1
    Possible Duplicate: http://stackoverflow.com/q/1636355/1369473 – Fr0zenFyr Jun 27 '14 at 11:56
  • 3
    Want you want is probably called the cartesian product. – Adder Jun 27 '14 at 11:58
  • Do your say recursive because the length of the `options` array is not always `3`? – PeterKA Jun 27 '14 at 12:10
  • This question already has an answer here: http://stackoverflow.com/a/12628791/1355315 – Abhitalks Jun 27 '14 at 12:16
  • Thanks for pointing out the name. After looking for Cartesian Product, i have found this small and great library: https://github.com/dankogai/js-combinatorics It is what i was looking for. – AFRC Jun 27 '14 at 15:51

3 Answers3

3

This also works:

printOption(options,0,"");


function printOption(options, i, string)
{
    if(i>=options.length)
    {
        console.log(string);
        return;
    }

    for(var j=0 ; j<options[i].items.length ; j++)
    {
        // console.log(options[i].items[j]);
        separator = string.length>0?" / ":"";
        printOption(options, i+1, string + separator + options[i].items[j]);
    }
}

DEMO

arthur.sw
  • 11,052
  • 9
  • 47
  • 104
1

Recursive solution:

function printOptions(options,level,line) {
    if (level >= options.length) {
        console.log(line);
    } else {
        if (line !== '') {
            line += ", ";
        }
        $.each(options[level].items, function() {
            printOptions(options, level+1, line + this);
        });
    }
}

printOptions(options,0,'');

Demo here

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

Try,

$.each(options[0].items, function (i, option) {
    $.each(options[1].items, function (j, option1) {
        $.each(options[2].items, function (k, option2) {
            console.log(option + "," + option1+"," + option2);
        });
    });
});

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130