Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recurse through a dynamic array

I am looking for a generalised solution for the following snippet::

var d = [[1,2,3], [1,2], [1,2,3,4,5,6]];

d[0].map((val1, index1) => {
    d[1].map((val2, index2) => {
        d[2].map((val3, index3) => {
            console.log(index1, index2, index3);
        })
    })
});

Here this consoles a possible combination for the 3 array elements.

Can we make it generalise, say e.g.

var d = [[1,2,3], [1,2], [1,2,3,4,5,6], [1,2,3,4]]; // k number of elements

Psuedo code::

let processor = (d) => {
    // implementation code
    // output will be the combination for 4 array elements this time.
}

Can someone help me design the process function? Looking for a generalised solution.Any help or lead is appreciable.

like image 890
Ayan Avatar asked Nov 29 '25 16:11

Ayan


2 Answers

You could use an iterative and recursive approach.

var d = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5, 6]],
    processor = array => {
        var iter = p => p.length < array.length ?
                array[p.length].forEach((_, i) => iter(p.concat(i))) :
                console.log(p);

        iter([]);
    };

processor(d);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 85
Nina Scholz Avatar answered Dec 02 '25 05:12

Nina Scholz


You can do as follows;

var cart = (a,b) => a.reduce((p,c) => p.concat(b.map(e => [].concat(c,e))),[]);
     arr = [[1,2,3], [1,2], [1,2,3,4,5,6], [8,9]],
     res = arr.reduce(cart);

console.log(JSON.stringify(res));
like image 22
Redu Avatar answered Dec 02 '25 06:12

Redu