Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run recursive function on Javascript array [duplicate]

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/

like image 577
AFRC Avatar asked Apr 21 '26 06:04

AFRC


1 Answers

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

like image 124
arthur.sw Avatar answered Apr 23 '26 19:04

arthur.sw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!