Reputation: 149
I want a new array based on the existing array. Basically, I am training to create Shopify variants based on textbox value. Right now what I am doing is to separate the textbox value by a comma and save in the array. Based on that arrays, I want a new variant array.
Variant arrays:-
variant_size = ['small','medium','big'];
variant_color = ['red','blue','green'];
variant_material = [];
variant_style = ['style1','style2'];
My expected output:-
new_array = [
{'small','red','style1'}
{'small','red','style2'}
{'small','blue','style1'}
{'small','blue','style2'}
{'small','green','style1'}
{'small','green','style2'}
{'medium','red','style1'}
{'medium','red','style2'}
{'medium','blue','style1'}
{'medium','blue','style2'}
{'medium','green','style1'}
{'medium','green','style2'}
{'big','red','style1'}
{'big','red','style2'}
{'big','blue','style1'}
{'big','blue','style2'}
{'big','green','style1'}
{'big','green','style2'}
];
If the array is empty like variant_material in the above example, skip that array. Below is a screenshot of the textbox which I have.
This is what I am training to acchive and This is my text fields.
Upvotes: 0
Views: 557
Reputation: 46602
Try this, simply loop over each array you want to make permutations for.
You need to change the source array and the expected output, as both are not valid javascript.
// object of variant's
const variant = {
size: ['small', 'medium', 'big'],
color: ['red', 'blue', 'green'],
material: [],
style: ['style1', 'style2']
}
// loop
let variants = []
for (let size of variant.size)
for (let color of variant.color)
for (let style of variant.style)
variants.push([size, color, style])
// result
console.log(JSON.stringify(variants, null, 2))
Upvotes: 1