I am in need of creating an array that contains all possible combinations of attribute values.
Here is an example of my attributes/values object:
let attr = {
color: ['red', 'green', 'blue'],
sizes: ['sm', 'md', 'lg'],
material: ['cotton', 'wool']
}
The goal is to generate an array containing all potential combinations like the following:
color | size | material
-----------------------------
red sm cotton
red sm wool
red md cotton
red md wool
red lg cotton
red lg wool
blue sm cotton
blue sm wool
blue md cotton
blue md wool
blue lg cotton
blue lg wool
green sm cotton
green sm wool
green md cotton
green md wool
green lg cotton
green lg wool
The number of attribute types and values can vary (minimum one). How do I accomplish this task?
This is the current code snippet I have been working on:
// keys = ['color', 'sizes', 'material']
// attributes object as shown above
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let values = attr[key];
// iterate through each value
for (let j = 0; j < values.length; j++) {
// for each value, loop over all keys
for (let k = 0; k < keys.length; k++) {
if (i === k) {
continue;
}
for (let l = 0; l < values.length; l++) {
// What should I do next?
// Unsure if I am on the right track here?
}
}
}
}