EN
JavaScript - all possible combinations tree for 2D array items
9
points
In this article we would like to show hw to create combinations tree for 2D array items.
Simple visualisation:
// input:
[
['a', 'b', 'c'],
['1', '2'],
['w', 'x', 'y', 'z']
]
// output:
{
"a": {
"1": {
"w": true,
"x": true,
"y": true,
"z": true
},
"2": {
"w": true,
"x": true,
"y": true,
"z": true
}
},
"b": {
"1": {
"w": true,
"x": true,
"y": true,
"z": true
},
"2": {
"w": true,
"x": true,
"y": true,
"z": true
}
},
"c": {
"1": {
"w": true,
"x": true,
"y": true,
"z": true
},
"2": {
"w": true,
"x": true,
"y": true,
"z": true
}
}
}
Quick solution:
// ONLINE-RUNNER:browser;
var CombinationsUtils = {
createTree: function(array, position) {
if (position == null) {
position = 0;
}
if (position < array.length) {
var item = array[position];
var tree = {};
for (var i = 0; i < item.length; ++i) {
var value = item[i];
tree[value] = this.createTree(array, position + 1);
}
return tree;
}
return true;
},
containsCombination: function(tree, path) {
var node = tree;
for (var i = 0; i < path.length; ++i) {
if (node == null) {
return false;
}
node = node[path[i]]
}
return node == true;
}
};
// Usage example:
var array = [
['a', 'b', 'c'],
['1', '2'],
['w', 'x', 'y', 'z']
];
var tree = CombinationsUtils.createTree(array);
console.log('a 1 w: ' + CombinationsUtils.containsCombination(tree, ['a', '1', 'w'])); // true
console.log('a 3 w: ' + CombinationsUtils.containsCombination(tree, ['a', '3', 'w'])); // false
console.log('\nTree: ' + JSON.stringify(tree, null, 4));