Search code examples
javascriptarrayssortingcounting

sort possible options javascript array using fundamental counting principle


I have 3 arrays which contains different values. and want get possible order options using. I want to make a variation for my product, so when I select 3 variations, javascript will generate the possible sorting options. eg:-

colors=['black','red','yellow'];
sizes=['s','m','l','xl','2xl','3xl'];
status=['used','new'];
let array1=['black','red','yellow'];
let array2=['s','m','l','xl','2xl','3xl'];
let array3=['used','new'];
var all=[];
all.push(colors.toString());
all.push(sizes.toString());
all.push(status.toString())
for (var i = 1; i <= 3; i++) {
    
console.log(option);
}

expecting:

[
    'black,s,used',
    'black,s,new',
    'black,m,used',
    'black,m,new',
    'black,l,used',
    'black,l,new',
    'black,xl,used',
    'black,xl,new',
    'black,2xl,used',
    'black,2xl,new',
    'black,3xl,used',
    'black,3xl,new',
    'red,s,used',
    'red,s,new',
    'red,m,used',
    'red,m,new',
    'red,l,used',
    'red,l,new',
    'red,xl,used',
    'red,xl,new',
    'red,2xl,used',
    'red,2xl,new',
    'red,3xl,used',
    'red,3xl,new',
    'yellow,s,used',
    'yellow,s,new',
    'yellow,m,used',
    'yellow,m,new',
    'yellow,l,used',
    'yellow,l,new',
    'yellow,xl,used',
    'yellow,xl,new',
    'yellow,2xl,used',
    'yellow,2xl,new',
    'yellow,3xl,used',
    'yellow,3xl,new',
    ]

I want to use product variation when a person chooses the 3 variations I mentioned above.


Solution

  • This is how you calculate variations for your products

    let colors=['black','red','yellow']; let
    sizes=['s','m','l','xl','2xl','3xl']; let status=['used','new']; let
    variations = [] for(let k=0;k<colors.length;k++){
        for(let i=0; i< sizes.length;i++){
            for (let j=0; j<status.length;j++){
                variations.push(`${colors[k]}-${sizes[i]}-${status[j]}`)
            }
        } }
    
    console.log(variations)