I'm trying to write a script that will return me all possible combinations for some parameters. Here is what I currently have. The problem is that length of tagsLoop list can change and then I would need another for loop inside the most nested loop. And then another one and another one. I'm adding screenshot with variables that I use to loop over.
Edit: added working snippet
var tagsLoop = ["mobile_size", "desktop_size", "tag_test"]
var bigArray = [{tag: "mobile_size", key: "size", val: "6"},
{tag: "mobile_size", key: "size", val: "2"},
{tag: "desktop_size", key: "size", val: "10"},
{tag: "desktop_size", key: "size", val: "20"},
{tag: "tag_test", key: "oracle", val: ""},
{tag: "tag_test", key: "pros", val: ""}]
for (var i = 0; i < bigArray.length; i++) {
if (bigArray[i]['tag'] == tagsLoop[0]) {
var part1 = bigArray[i]['key'] + '=' + bigArray[i]['val']
for (var j = 0; j < bigArray.length; j++) {
if (bigArray[j]['tag'] == tagsLoop[1]) {
var part2 = "&" + bigArray[j]['key'] + '=' + bigArray[j]['val']
for (var k = 0; k < bigArray.length; k++) {
if (bigArray[k]['tag'] == tagsLoop[2]) {
var part3 = "&" + bigArray[k]['key'] + '=' + bigArray[k]['val']
console.log(part1, part2, part3)
}
}
}
}
}
}
asked Sep 7, 2018 at 15:29
AlienDeg
1,3893 gold badges15 silver badges30 bronze badges
1 Answer 1
You could get the grouped data first and the build new arrays with the combinations of the wanted items and their values.
function getCartesian(array, keys) {
var temp = array.reduce((r, { tag, key, val }) => {
(r[tag] = r[tag] || []).push([key, val].join('='));
return r;
}, Object.create(null));
return keys
.map(k => temp[k])
.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
.map(a => a.join('&'));
}
var array = [{ tag: "mobile_size", key: "size", val: "6" }, { tag: "mobile_size", key: "size", val: "2" }, { tag: "desktop_size", key: "size", val: "10" }, { tag: "desktop_size", key: "size", val: "20" }, { tag: "tag_test", key: "oracle", val: "" }, { tag: "tag_test", key: "pros", val: "" }],
tags = ["mobile_size", "desktop_size", "tag_test"],
result = getCartesian(array, tags);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
answered Sep 7, 2018 at 15:58
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
tagLoopchange during your iterations? And what does it mean?