Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get all possible combinations using javascript

i'm currently stuck on this problem,

suppose there is an array arr4(length is not fixed). I need to find all combinations of its element.

expected output is:

4-16D-5d 
4-16D-5e
4A-16D-5d
4A-16D-5e
4B-16D-5d
4B-16D-5e

4-15D-5d
4-15D-5e
4A-15D-5d
4A-15D-5e
4B-15D-5d
4B-15D-5e

What i tried is:

arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']]; //may contains more elements
alert("arr4 "+arr4);
for(var k=0;k<arr4.length;k++){
    alert("k "+k);
    arr_v=arr4[k]
    alert("arrv"+arr_v);
    alert ("arrv lengt"+arr_v.length);
    for(var z=0;z<arr_v.length;z++){
        m=1;
        while(m<arr4.length){
            var test=arr4[m];
            for(var n=0;n<test.length;n++)
                alert(arr_v[z]+"<TEST>"+test[n]);
        }
        m++;
    }
}   

I kind of found a solution:

function product() {
    return Array.prototype.reduce.call(arguments, function(as, bs) {
        return [a.concat(b) for each (a in as) for each (b in bs)]
    }, [[]]);
}

BUT

arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(['4','4A','4B'],['16D','15D'],['5d','5e']);

The above works but the following don't work:

arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(arr4);

Anyone please suggest a solution

edit:solution here

like image 708
j.b Avatar asked Dec 05 '25 11:12

j.b


1 Answers

You can compute the cartesian product of each sub-array. See this question and its answer

I tried it out, and since it goes off the length of each array, it should work no matter how many elements are in each list and return you a list of each product.

like image 90
Charlie G Avatar answered Dec 07 '25 00:12

Charlie G



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!