0

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.

2
  • 1
    [{'small','medium','big'}] etc is not valid. what have you tried to generate your expected output? Commented Oct 6, 2020 at 16:14
  • axios.post('/productData') .then(response => { this.variant_size = response.data.variants.variant_size.split(","); this.variant_color = response.data.variants.variant_color.split(","); }); let variant_size = [{'variant_size' : this.variant_size}]; let variant_color = [{'variant_color' : this.variant_color}]; what I am doing right now is fetch the textbox value and slipt by comma and store into the array Commented Oct 6, 2020 at 16:18

1 Answer 1

1

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))

Sign up to request clarification or add additional context in comments.

4 Comments

How can I check if the array is undefined in the loop variant_color: [Array(3)] variant_material: [undefined] variant_size: [Array(3)] variant_style: [undefined] variant_title: [undefined]
how are you making that?
In the above code, you didn't mention material in for loop. how can I skip the for loop for an empty array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.