One approach to generating an array of strings with a hierarchical structure for all possible combinations in JavaScript is to use nested loops to iterate through each level of the hierarchy and generate all possible combinations at each level. The resulting array can then be combined with the parent arrays to create a nested hierarchy.
Here is an example implementation:
function generateHierarchy(levels, options) {
let results = [[]];
for (let i = 0; i < levels.length; i++) {
let levelOptions = options[levels[i]];
let temp = [];
for (let j = 0; j < results.length; j++) {
for (let k = 0; k < levelOptions.length; k++) {
temp.push(results[j].concat(levelOptions[k]));
}
}
results = temp;
}
return results;
}
// Example usage
let options = {
"level1": ["A", "B"],
"level2": ["1", "2", "3"],
"level3": ["X", "Y"]
};
let levels = Object.keys(options);
let hierarchy = generateHierarchy(levels, options);
console.log(hierarchy);
// Output:
// [
// ["A", "1", "X"],
// ["A", "1", "Y"],
// ["A", "2", "X"],
// ["A", "2", "Y"],
// ["A", "3", "X"],
// ["A", "3", "Y"],
// ["B", "1", "X"],
// ["B", "1", "Y"],
// ["B", "2", "X"],
// ["B", "2", "Y"],
// ["B", "3", "X"],
// ["B", "3", "Y"]
// ]
In this implementation, generateHierarchy
takes two arguments: levels
, an array of strings representing the levels of the hierarchy, and options
, an object where each key represents a level and the value is an array of possible options at that level.
The function starts by initializing an array with a single empty array, representing the root of the hierarchy. It then iterates through each level using a for
loop, generating all possible combinations of options at each level using nested for
loops. The results are stored in a temporary array and then reassigned to results
, which contains all possible combinations of the hierarchy.
Finally, the function returns the resulting hierarchy array. In the example usage, we pass in an object with three levels and three possible options at each level, and the resulting hierarchy array contains all 12 possible combinations.
Asked: 2023-01-24 11:00:00 +0000
Seen: 7 times
Last updated: Jul 04 '22