I have an array of objects, e.g.
var arr = [
{"a": "x"},
{"b": "0"},
{"c": "k"},
{"a": "nm"},
{"b": "765"},
{"ab": "i"},
{"bc": "x"},
{"ab": "4"},
{"abc": "L"}
];
Let's say I am only interested in objects whose keys correspond to var input = ["ab", "bc"]
. It means that I want to extract all possible subarrays with result[i].length == 2
in the following way:
var result = [
[{"ab": "i"}, {"bc": "x"}],
[{"ab": "4"}, {"bc": "x"}] // or [{"bc": "x"}, {"ab": "4"}]
];
— that is, the order of objects in subarrays is absolutely not important: I am only interested in the fact that each subarray contains two objects — {"ab": ...}
and {"bc": ...}
.
If I was interested in var input = ["a","a","ab"]
, the result should be like this:
var result = [
[{"a": "x"}, {"a": "nm"}, {"ab": "i"}],
[{"a": "x"}, {"a": "nm"}, {"ab": "4"}]
];
I cannot find the way to achieve the desired result (assuming that input.length
may be much greater than 2 or 3 — even 15–20 may be not enough) without factorial-level amount of computations, which is not physically possible. Is there a way to have some reasonable performance for solving such a problem?
Important note: yes, obviously, for relatively large values of input.length
there theoretically may be possible to have very huge numbers of possible combinations, but in practice, result.length
will always be reasonably small (maybe 100–200, I even doubt that it could reach 1000...). But for safety, I would want to just set some limit (say, 1000), such that as soon as result.length
reaches this limit, the function just returns the current result
and stops.