Languages
[Edit]
EN

JavaScript - all possible combinations tree for 2D array items

9 points
Created by:
Marcin
18490

In this article we would like to show hw to create combinations tree for 2D array items.

// 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('Tree: ' + JSON.stringify(tree, null, 4));

See also

  1. JavaScript - all possible combinations for 2D array items 
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join