Javascript: Compute the number of product variants based on attributes

时间:2016-08-31 12:34:13

标签: javascript algorithm e-commerce variants

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.

1 个答案:

答案 0 :(得分:1)

不是传递原始数组,而是克隆它并将克隆数组作为参数传递。

 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;
    }
相关问题