admin管理员组文章数量:1318328
I'm trying to get a result looking something like this: Miniors | Boys | 54kg - 62kg
where every value delimited by a pipe | es from an array containing a certain "type of restriction". For example: ageGroups, genders, weightClasses
(as seen above).
The way I'm able to get this result right now is if I hard code the nested forEach-loops (using underscorejs), but this means I have to now how many arrays I have to loop over to get wanted result. This works "fine":
var categories = [];
_.each(ageGroups, function(ageGroup) {
_.each(gender, function(gender) {
_.each(weightClasses, function(weightClass) {
categories.push(ageGroup.name + ' | ' + gender.name + ' | ' + weightClass.name);
});
});
});
The output is an array (categories) with all the possible binations of the restriction arrays.
Now, my problem is that I need a way to do the same with an unknown number of restriction arrays. My guess for a proper solution is recursion, BUT I haven't been able to produce anything that actually works since I'm not able to wrap my head around recursion just yet :)
A fiddle prepared with some test data can be found here: jsFiddle. The fiddle uses angular for some simple databinding and debugging the result output and underscorejs for handling the arrays.
I'm trying to get a result looking something like this: Miniors | Boys | 54kg - 62kg
where every value delimited by a pipe | es from an array containing a certain "type of restriction". For example: ageGroups, genders, weightClasses
(as seen above).
The way I'm able to get this result right now is if I hard code the nested forEach-loops (using underscorejs), but this means I have to now how many arrays I have to loop over to get wanted result. This works "fine":
var categories = [];
_.each(ageGroups, function(ageGroup) {
_.each(gender, function(gender) {
_.each(weightClasses, function(weightClass) {
categories.push(ageGroup.name + ' | ' + gender.name + ' | ' + weightClass.name);
});
});
});
The output is an array (categories) with all the possible binations of the restriction arrays.
Now, my problem is that I need a way to do the same with an unknown number of restriction arrays. My guess for a proper solution is recursion, BUT I haven't been able to produce anything that actually works since I'm not able to wrap my head around recursion just yet :)
A fiddle prepared with some test data can be found here: jsFiddle. The fiddle uses angular for some simple databinding and debugging the result output and underscorejs for handling the arrays.
Share Improve this question edited Nov 2, 2014 at 20:08 David G 96.9k41 gold badges172 silver badges257 bronze badges asked Nov 2, 2014 at 19:59 aupaup 8107 silver badges19 bronze badges 3-
Try not to use side-effects (i.e.
push
ing to a globalcategories
array), but insteadreturn
from each step and usemap
(andflatten
) – Bergi Commented Nov 2, 2014 at 20:32 - Hmm.. Okey. Flatten wont be of any use here since I need a bination of the different values from the different arrays. But map might be something.. Even though I can't see how it would solve the problem I'm facing with a dynamic amount of arrays. You care to elaborate? – aup Commented Nov 2, 2014 at 20:43
-
Try to use
map
(even in a non-generic way) and you will see what you need theflatten
for. Then, make a function that takes thegroups
, the current group's index (the "nesting level") and the current names of the visited groups. The base case (when the level of nesting has reached the length of thegroups
) would then return those current names (joined by ` | `), the recursive case - you'll figure out. – Bergi Commented Nov 2, 2014 at 20:55
2 Answers
Reset to default 5I recently wrote a recursive function to create all binations of arrays. You would have to translate your data into an array of arrays that my function uses, but that shouldn't be difficult.
Anyway, here's the code with a runnable example:
var v = [['Miniors','Kadettes','Juniors', 'Seniors'], ['Boys','Girls','Men','Women'],['54kg - 62kg','64kg - 70kg','71kg - 78kg','79kg - 84kg']];
var bos = createCombinations(v);
for(var i = 0; i < bos.length; i++) {
document.getElementsByTagName("body")[0].innerHTML += bos[i] + "<br/>";
}
function createCombinations(fields, currentCombinations) {
//prevent side-effects
var tempFields = fields.slice();
//recursively build a list binations
var delimiter = ' | ';
if (!tempFields || tempFields.length == 0) {
return currentCombinations;
}
else {
var binations = [];
var field = tempFields.pop();
for (var valueIndex = 0; valueIndex < field.length; valueIndex++) {
var valueName = field[valueIndex];
if (!currentCombinations || currentCombinations.length == 0) {
var binationName = valueName;
binations.push(binationName);
}
else {
for (var binationIndex = 0; binationIndex < currentCombinations.length; binationIndex++) {
var currentCombination = currentCombinations[binationIndex];
var binationName = valueName + delimiter + currentCombination;
binations.push(binationName);
}
}
}
return createCombinations(tempFields, binations);
}
}
function iterate(lists, fn)
{
var values = [];
function process(listIndex)
{
var list = lists[listIndex];
// no list? create the value
if (!list)
{
fn.apply(null, values);
return;
}
for (var i = 0; i < list.length; i++)
{
values[listIndex] = list[i];
process(listIndex+1);
}
}
process(0);
}
here is a working example based on the data mentioned in your question: http://jsbin./boqucu/2/edit
本文标签: javascriptDynamic nested for loops to be solved with recursionStack Overflow
版权声明:本文标题:javascript - Dynamic nested for loops to be solved with recursion - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742042657a2417619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论