0

I want to generate all the possible variants a product can have based on the attributes like color, size, etc. I'm trying to implement the solution given by profitphp in javascript but not getting the desired results.

Here is what I implemented:

var data = [['red', 'blue', 'green'],['small', 'medium', 'large']];

result = generateVariants(data);
console.log(result);

function generateVariants(data,prefix) {
    if (typeof prefix === 'undefined') {
        prefix = '';
    }

    var result = [];
    var attribute = data.shift();

    $.each(attribute, function(key,val) {
        if (data instanceof Array && data.length > 0) {
            result = result.concat(generateVariants(data, val + ' '));
        }
        else {
            result.push(prefix + val);
        }
    });

    return result;
}

Expected Result:

["red small", "red medium", "red large", "blue small", "blue medium", "blue large", "green small", "green medium", "green large"]

Instead, I'm getting this:

["red small", "red medium", "red large", "blue", "green"]

Any help is greatly appreciated. Thanks.

Community
  • 1
  • 1
codeit
  • 111
  • 8
  • 2
    All you need is to calculate cartesian product of your input array to get possible combinations. Perhaps this link can help. Look at the answer.http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript – Farooq Ahmed Khan Aug 31 '16 at 12:40
  • @Farooq Thank you for pointing me in the right direction. – codeit Sep 01 '16 at 07:37
  • Hey check my code [here](https://stackoverflow.com/questions/66521397/create-product-variants-based-on-attributes) – Muhammad Taseen Mar 07 '21 at 21:19

1 Answers1

1

Instead of passing the original array, clone it and pass the cloned array as argument.

 var data = [['red', 'blue', 'green'],['small', 'medium', 'large']];

    result = generateVariants(data);
    console.log(result);

    function generateVariants(data,prefix) {
        if (typeof prefix === 'undefined') {
            prefix = '';
        }

        var result = [];
        var attribute = data.shift();

        $.each(attribute, function(key,val) {
            if (data instanceof Array && data.length > 0) {




              // Instead of passing the original array, clone it and pass the cloned array as argument.
     _data = data.slice(0);



              result = result.concat(generateVariants(_data, val + ' '));
            }
            else {
                result.push(prefix + val);
            }
        });

        return result;
    }
user3733648
  • 1,323
  • 1
  • 10
  • 25