Jul 06, 2021 01:58 AM
Hello! :slightly_smiling_face:
I have a database for products and in there I have two tables Products and Variants.
I would need a new record to be created based on multiple select fields.
At the moment the script works perfectly if a record needs to be created based on one multiple records field. But in my case, I would need up to 3 fields to be counted.
E.g.
I have a Product A that has 3 color options + 4 sizes + 2 add-on options.
When I run the script, it needs to create 342=24 new records in table Variants.
The current script doesn‘t allow to create 24 records at once based on different fields.
Is there an extended script available that could fit my needs? Or what could be a solution for it?
Thank you!
Jul 06, 2021 04:21 AM
@Kateryna_Pysmenska - I did a quick Google and came across this (+ there’s a lot of variants of this out there):
const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
let result = cartesian([1,2],[10,20],[100,200,300]);
console.log(result)
If you can wrangle you colour, size and add-on options into 3 arrays, then the cartesian
function will give you all combinations of the elements within.
I need to do a bit of reading on flatMap and flat, but even without fully understanding these, it definitely does the job.
Jul 07, 2021 06:39 AM
Welcome to the community, @Kateryna_Pysmenska! :grinning_face_with_big_eyes: If @JonathanBowen’s comment provided the answer you were seeking, please mark his comment as the solution to your question. This helps others who may be searching with similar questions. Thanks!