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.